Вы находитесь на странице: 1из 2

Binary Search Algorithm- Fundamentals, Implementation and AnalysisHitesh Garg|May 15, 2015|

algorithms|1 CommentBinary Search Algorithm and its ImplementationIn our previous tutorial we
discussed aboutLinear search algorithm which is themost basic algorithm of searching which has some
disadvantages in terms of time complexity,so to overcome them to a levelan algorithm based on
dichotomic (i.e. selection between two distinct alternatives) divide and conquer techniqueis used i.e.
Binarysearch algorithm and it is used to find an element in asorted array(yes, it is a prerequisite for this
algorithm and a limitation too).In this algorithm we use the sorted array so as to reduce the time
complexity to O(log n). In this, size of the elements reduce to half after each iteration and this is
achieved by comparing the middle element with the key and if they are unequal then we choose the
first or second half, whichever is expected to holdthe key (if available) based on the comparison i.e. if
array is sorted in an increasing manner and the key is smaller than middle element than definitely if key
exists, it will be in the first half, we chose itand repeat same operation again and again until key is found
or no more elements are left in the array.Recursive Pseudocode:123456789101112// initially called with
low = 0, high = N – 1BinarySearch_Right(A[0..N-1], value, low, high) {// invariants: value >= A[i] for all i <
lowvalue < A[i]forall i > highif(high < low)returnlowmid = low +((high – low) / 2)// THIS IS AN
IMPORTANT STEP TO AVOID BUGSif(A[mid] > value)returnBinarySearch_Right(A, value, low, mid-
1)elsereturnBinarySearch_Right(A, value, mid+1, high)}Iterative
Pseudocode:1234567891011121314BinarySearch_Right(A[0..N-1], value) {low = 0high = N - 1while(low
<= high) {// invariants: value >= A[i] for all i < lowvalue < A[i]forall i > highmid = low +((high – low) / 2)//
THIS IS AN IMPORTANT STEP TO AVOID BUGSif(A[mid] > value)high = mid - 1elselow = mid +
1}returnlow}Asymptotic AnalysisSince this algorithm halves the no of elements to be checked after
every iteration it will take logarithmic time to findany element i.e. O(log n) (where n is number of
elements in the list) and its expected cost is also proportional tolog nprovided that searching and
comparing cost of all the elements is sameData structure used -> ArrayWorst case performance -> O(log
n)Best case performance -> O(1)Average case performance -> O(log n)Worst case space complexity ->
O(1)So the idea is-1.Compare the key (element to be searched) with the mid element.2.If key matches
with middle element, we return the mid index.3.Else If key is greater than the mid element, then key can
only lie in right half subarray after the mid element. So we recur for right half.4.Else (x is smaller) recur
for the left half until there are no more elements left in the array.RECURSIVE Implementation of Binary
search in C programming
language1234567891011121314151617181920212223242526272829303132333435#include
<stdio.h>// A recursive binary search function. It returns location of x in// given array arr[l..r] is present,
otherwise -1intbinarySearch(intarr[],intl,intr,intx){if(r >= l){intmid = l + (r - l)/2;// If the element is
present at themiddle itselfif(arr[mid] == x) returnmid;// If element is smaller than mid, then it can only
be present// in left subarrayif(arr[mid] > x)returnbinarySearch(arr, l, mid-1, x);// Else the element can
only be present in right subarrayreturnbinarySearch(arr, mid+1, r, x);}// We reach here when element is
not present in arrayreturn-1;}intmain(void){intarr[] = {2, 3, 4, 5, 10, 15, 25, 40};intn
=sizeof(arr)/sizeof(arr[0]);intx = 15;intresult = binarySearch(arr, 0, n-1, x);(result == -1)?printf("Element is
not present in array"):printf("Element is present at index %d", result);return0;}Output:-Element is
present at index 5ITERATIVE Implementation of Binarysearch in C programming
language1234567891011121314151617181920212223242526272829#include <stdio.h>// A iterative
binary search function. It returns location of x in// given array arr[l..r] if present, otherwise
-1intbinarySearch(intarr[],intl,intr,intx){while(l <= r){intm = l + (r-l)/2;if(arr[m] == x)returnm; // Checkif x
is present at midif(arr[m] < x) l = m + 1;// If x greater, ignore left halfelser = m - 1;// If x is smaller, ignore
right half}return-1;// If this line executes, then search was unsuccessful i.e. element is not
present}intmain(void){intarr[] = {2, 3, 4, 5, 10, 15, 25, 40};intn =sizeof(arr)/sizeof(arr[0]);intx =
15;intresult = binarySearch(arr, 0, n-1, x);(result == -1)?printf("Element is not present in
array"):printf("Element is present at index %d", result);return0;}Output:-Element is present at index
5Implementation of BinarySearch(Iterative and Recursivemethods) in JavaIn Java Binary Search method
is already implemented and it is recommended that we should use java.util.Arrays.binarySearch(//A lot
of overloaded functions). See complete list of functions here – Oracle –
java.util.Arrays12345678910111213141516171819202122232425262728293031323334353637383940
packagecom.codingeek.algorithms;publicclassRecursiveBinarySearchAlgorithm{publicstaticintrecursiveBi
narySearch(int[] sortedArray,intstart,intend,intkey) {if(start < end) {intmid = start + (end - start) /2;if(key
< sortedArray[mid]) {returnrecursiveBinarySearch(sortedArray, start, mid, key);}elseif(key >
sortedArray[mid]) {returnrecursiveBinarySearch(sortedArray, mid+1, end , key);}else{returnmid;}}return-
1;}publicstaticvoidmain(String[] args) {int[] arr1 = {2,45,100,190,280,500,670,700,999};intindex =
recursiveBinarySearch(arr1,0,arr1.length,45);if(index != -1){System.out.println("Found 45 at"+index+"
index");}else{System.out.println("Element not found");}index =
recursiveBinarySearch(arr1,0,arr1.length,99);if(index != -1){System.out.println("Found 999 at "+index+"
index");}else{System.out.println("Element not found");}}}Output:-Found 45 at 1 indexElement not
foundIMPORTANTNOTE :-One important point was that while finding the mid-point we do (mid = low +
((high – low) / 2)) while this can also be achieved by simply doing (mid=(high + low) / 2)). This is because
if both the numbers i.e. low and high are too high such that their sum reaches above the range of
datatype used then it will producean error as it will become a negative number and no array index of
negative value is possible.For ex– if low = 32,000 and high = 32,700 thenmid = (32000 + 32700)/2 =
64700/2In C Language => 64700 for an “int” type is equal to (-835)i.e. (-835)/2 = (-417), which will
produce error.So to avoid such situations we add the half of difference between the two to the lower
value which ensures that we never encounter such a situation.Doshare the wisdom and motivate us to
keep writing such online tutorials for free and do comment if anything is missing or wrong or you need
any kind of help.Keep Learning..Happy Learning..Tags:Algorithm pseudocode,algorithms,algorithms and
data structure,algorithms examples,algorithms implementation in c,algorithms implementation in
java,searching algorithmsRelated PostsWhat are Algorithms and why arethey of utter importance?0
Comments|Apr 18, 2015Bubble Sort Algo

Вам также может понравиться