Professional Documents
Culture Documents
Binary Search
Binary Search
In computer science, binary search, also known as half-interval search, logarithmic search, or binary
chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search
compares the target value to the middle element of the array.
In binary search array elements should be sorted or for example in an ascending order.
Like linear search array elements in binary search should also be unique.
4 8 10 15 18 21 24 27 29 33 34 37 39 40 41
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Key – the element that we are searching for inside the array.
Variable low is the beginning of the index which here in our example is [0]
Variable high is the last index of out array list, in our example is [14]
Example 1:
Find key = 18
low high get mid mid Get new l and h New high and Low
0 14 m = (0 + 14 ) / 2 7 high = mid - 1 7–1=6
0 6 m = (0 + 6 ) / 2 3 low = mid + 1 3+1=4
4 6 m = (4 + 6 ) / 2 5 high = mid – 1 5–1=4
and 3+1=4
low = mid + 1
4 4 m = (4 + 4) / 2 4
Result key 18 = index 4
Example 2:
Find key = 34
low high get mid mid Get new l and h New high and Low
0 14 m = (0 + 14) / 2 7 low = mid + 1 7+1=8
8 14 m = (8 + 14) / 2 11 high = mid - 1 11 – 1
8 10 m = (8 + 14) / 2 9 low = mid + 1 9+1
10 10 m = (10+ 10) / 2 10
Result key 34 = index 10
Example 3: an unsuccessful search
Find key = 25
low high get mid mid Get new l and h New high and Low
0 14 m = (0 + 14) / 2 7 high = mid - 1 7-1=6
0 6 m = (0 + 6) / 2 3 low = mid + 1 3+1=4
4 6 m = (4 + 6) / 2 5 low = mid + 1 5+1=6
6 6 m = (6 + 6) / 2 6 low = mid + 1 6+1=7
and
high = mid - 1 6-1=6
Unsuccessful
Pseudo Code
binarySearch(low, high, key){
}
Do it until the element is found in order
to do this we should use a loop like the
pseudo code below:
struct Array{
int A[10];
int size;
int length;
};
int main(){
getch();
return 0;
}