First and foremost step is to check weather the array is sorted or not. If sorted then proceed, if not then apply sorting method to sort it first and then proceed with further mentioned steps.(bubble sort)
Take the element to be searched for in a variable x
Set two pointers low and high at the lowest and highest positions respectively.
Find the middle element “mid” of the array by the formula → mid = high + low / 2
If x==mid, then return the mid as the output.
If x > mid, compare x with the middle element to the element on the right side of the mid element. This is done by setting low = mid + 1
Else, compare x with the middle element of the left side of the mid. This is done by
high = mid - 1
Repeat the steps 3 - 6 until low and high are equal (low == high)
write “x is found”
Exit
#include <stdio.h>
int binarySearch(int arr[], int L, int r, int x){
while (L <= r){
int mid = L + (r-1)/2;
if (arr[mid]== x){
return mid;
}
if (arr[mid] < x){
L = mid + 1;
}
else{
r = mid - 1;
}
return mid;
}
}
int main (){
int arr[] = {0,2,8,12,30,41,50};
int n = sizeof(arr)/sizeof(arr[0]);
int x;
printf("Enter the number to search : ");
scanf("%d", &x);
int result = binarySearch(arr, 0, n-1, x);
if (result == -1){
printf("Element is not present in array");
}
else{
printf("Element is present at index %d", result);
}
return 0;
}