- oanaunciuleanu

# Exponential Search in C++

Exponential search is an algorithm used for finding a value in an array. The array must be ordered. This algorithm is based on the Binary Search Algorithm. This search jumps 2^I elements at every iteration. I is the value of loop control variable, and it verifies if the search element is between the last and the current jumps.

This algorithm, also known as doubling search, galloping search, Struzik search is used for searching **sorted**, **unbounded** (infinite) **lists**.

To explain it in a simpler way, we have to start with a sub-array of size 1, compare its last element with the searched value, and then double the size to 2, and then to 4, until the last element of the sub-array is not greater. In this way, the searched value must be between i/2 and I, this is because in the previous iteration we couldn’t find a greater value.

// Exponential Search #include <iostream>usingnamespacestd;intbinarySearch(intarrayOfNumbers[],intsearchForNumber,intleft,intright) {if(right >= left) {intmiddle = left + (right - left) /2;if(arrayOfNumbers[middle] == searchForNumber) { printf("The number %d is found at index %d", searchForNumber, middle);returnmiddle; }if(arrayOfNumbers[middle] > searchForNumber) {returnbinarySearch(arrayOfNumbers, searchForNumber, left, middle -1); }returnbinarySearch(arrayOfNumbers, searchForNumber, middle +1, right); } printf("The number %d was not found in the array", searchForNumber);return-1; }intexponentialSearch(intarrayOfNumbers[],intnumberOfElements,intsearchForNumber) { // Check if the desired number is on first positionif(arrayOfNumbers[0] == searchForNumber)return0; //ad a variable i for the jumpinti =1;while(i < numberOfElements && arrayOfNumbers[i] <= searchForNumber) { // multiply i each iteration i = i*2; } // apply binary search in the interval where the value is between i/2 and ireturnbinarySearch(arrayOfNumbers, searchForNumber,0, numberOfElements -1); }intmain(void) {intarrayOfNumbers[] = {1,4,9,15,22,25,38,42,77,85};intsearchForNumber =77;intnumberOfElements =sizeof(arrayOfNumbers) /sizeof(arrayOfNumbers[0]);intresult = exponentialSearch(arrayOfNumbers, numberOfElements, searchForNumber); }