Binary search is most common and simple technique use to search specific number in array. Binary search requires sorted array hence the complexity of binary search O(log n) is better than most of the searching algorithm.binary search first compare the search value with middle element of array if match found then program terminates.if search value is smaller than middle element then it will search that value in left part of array otherwise it will search that value in right part of array.
Space complexity: O(1)
Time complexity:
Space complexity: O(1)
Time complexity:
Best case
|
Average case
|
Worst case
|
O(1)
|
O(log n)
|
O(log n)
|
Example of Binary search:
search element 20 from below array:
10 20 30 40 50 60 70
here,
start=0 and end=6
mid=(0+6)/2=3
element at 3rd index(40) is middle elementsearch element is 30
30 < 40
now,
start=0 and end=mid-1=2
mid=(start+end)/2=1
element at 1st index is middle element
thus search element 20 is found at 1st index position.
Pseudo-code:
procedure binary_search
A = sorted array
n = size of array
x = value to be searched
Set first= 1
Set last= n
while x not found
if last < first
EXIT: x does not exists.
set mid = first + last / 2
if x > A[mid]
set first= mid + 1
if x < A[mid]
set last = mid - 1
if A[mid] = x
EXIT: x found at location mid
end while
end procedure
program of binary search:
Output:
Output of binary search program |
No comments:
Post a Comment