Binary Search
Binary Search
1. Iterative Method
2. Recursive Method
Initial array
Let x = 4 be the element to be searched.
2. Set two pointers low and high at the lowest and the highest positions
respectively. Setting pointers
3. Find the middle position mid of the array ie. mid = (low +
high)/2 and arr[mid] = 6.Mid element.
6. Else, compare x with the middle element of the elements on the left
side of arr[mid]. This is done by setting high to high = mid - 1.
Mid Element
8. x = 4 is found. Found
Mid Element Found
#include <stdio.h>
// Repeat until the pointers low and high meet each other
if (x == array[mid])
return mid;
if (x > array[mid])
low = mid + 1;
else
high = mid - 1;
return -1;
int main(void) {
if (result == -1)
printf("Not found");
else
return 0;
(Recursive Method)
// Binary Search in C
#include <stdio.h>
if (x == array[mid])
return mid;
if (x > array[mid])
return -1;
int main(void) {
int x = 4;
if (result == -1)
printf("Not found");
else
Output: