Binary Search: Search an element in sorted array
C program for binary search: Binary search works only in sorted array. Prerequisite of binary search is that array should be sorted. If you want to implement binary search in unsorted array then you should sort array using any sorting algorithm like merge sort, quick sort etc and then implement binary search.
C program for binary search:
C program for binary search:
#include<stdio.h> int BinarySearch(int arr[], int size, int num) { int low=0, high=size-1; int mid; while(low<=high) { /* for large size of array you can another formula to calculate mid; mid = low+(high-low)/2 */ mid = (high+low)/2; /* if find element at index mid then return mid */ if(arr[mid]==num) { return mid; } else { /* if number is greater then arr[mid] then low will be mid+1; for example if array is 1,2,3,4,5,6 and we are searching 5 then arr[mid] = 3 that is less then number. now array from index 0 to mid is not useful to search number */ if(num>arr[mid]) low=mid+1; else high=mid-1; } } /* if element is not in array then return -1 here we are returning index at which number is present so if number is not in array then we return -1 because -1 is not any index in array */ return -1; } int main() { int arr[]={12,15,17,20,28,35,46,67,76,79}; int size = sizeof(arr)/sizeof(arr[0]); int num; printf("Enter a number to search: "); scanf("%d",&num); int index=BinarySearch(arr,size,num); if(index==-1) { printf("Number is not in array: "); } else { printf("Number is at index %d",index); } return 0; }