When we look up a single order in the dictionary, we usually turn to a general position (let's say, turn to the middle) and start looking. If there's a word we want to turn to, it's good luck and the search is over. If the word we are looking for is still in front of this position, we will continue to search for this half of the previous dictionary, turn to a certain location (assuming One-fourth) and so on. This binary search works the same way. The corresponding algorithm is called binary search algorithm.
Iterative version algorithm:
//iterative binary search which returns index of elementintBinarysearchiterative (intArr[],intSizeintdata) { intLow =0; intHigh = size-1; intmid; while(low<=High ) {Mid= Low + (high-low)/2;//To avoid overflow by (low + high) if(Arr[mid] = =data)returnmid; Else { if(Arr[mid] <data) Low= Mid +1;//Search in right half Else High= Mid-1;//Search in left half } } return-1;}
Recursive version algorithm:
//recursive binary search which returns index of elementintBinarysearchrecursive (intArr[],intLowintHighintdata) { if(low<=High ) { intMID = low + (high-low)/2;//To avoid overflow if(Arr[mid] = =data)returnmid; Else { if(Arr[mid] <data)//search in right half. returnBinarysearchrecursive (arr, mid+1, high, data); Else //search in left half. returnBinarysearchrecursive (arr, Low, mid-1, data); } } return-1;}
Binary searches (binary search)