C Program to Binary Search in a Sorted Array
Binary search is an efficient algorithm to find a specific element in a sorted array. It works by repeatedly dividing the search interval in half. Here’s a simple C program to perform binary search on a sorted array Program : #include <stdio.h> #include <conio.h> Â void main( ) { int arr[10] = { 1, 2, 3, 9, 11, 13, 17, 25, 57, 90 } ; int mid, lower = 0 , upper = 9, num, flag = 1 ; printf ( “Array[] : 1, 2, 3, 9, 11, 13, 17, 25, 57, 90 \n” ) ; printf ( “Enter number to search: ” ) ; scanf ( “%d”, &num ) ; Â for ( mid = ( lower + upper ) / 2 ; lower <= upper ; mid = ( lower + upper ) / 2 ) { if ( arr[mid] == num ) { printf ( “The number is at position %d in the array.”, mid ) ; flag = 0 ; break ; } if ( arr[mid] > num ) upper = mid – 1 ; else lower = mid + 1 ; } Â if ( flag ) printf ( “Element is not present in the array.” ) ; Â getch( ) ; } Output :
C Program to Binary Search in a Sorted Array Read More »