Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Search.

Similar presentations


Presentation on theme: "Binary Search."— Presentation transcript:

1 Binary Search

2 Definition Also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. This algorithm is same as “guess number game”

3 Usage Cost of searching algorithm reduces to binary logarithm of the array length. For reference, log2( ) ≈ 20. in worst case, algorithm makes 20 steps to find a value in sorted array of a million elements.

4 Algorithm get the middle element;
if the middle element equals to the searched value, the algorithm stops; otherwise, two cases are possible: searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element. searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element.

5 Program #include<iostream> using namespace std; int const n=5; int arr[n]={1, 2, 3, 4, 6}; void binarySearch(int); void main() { int num; cin>>num; binarySearch(num); system("pause"); } void binarySearch(int num) { int low, high, mid; low=0; high=n-1;

6 Program continues while(low<=high) { mid=(low+high)/2; if(arr[mid]==num) cout<<"Found at"<<mid+1; break; } else if(arr[mid]<num) low=mid+1; high=mid-1; else { cout<<"Not found\n"; break; }

7 Recursive Algortihm int recursiveBinSearch(int arr[], int guess, int low, int high) { if(low>high) return -1; int mid=low+(high-low)/2; if(arr[mid]<guess) return recursiveBinSearch(arr, guess, mid+1, high); else if (arr[mid]>guess) return recursiveBinSearch(arr, guess, low, mid-1); else return mid; }


Download ppt "Binary Search."

Similar presentations


Ads by Google