Program For Binary Search
Program For Binary Search
#include<stdio.h> //Header file #include<conio.h> //Header file for clrscr() int bin_search(int b[50], int low, int high); int item, cost=0; void main() { int a[50],i,n,loc; //Declaration clrscr(); //Function to clear screen printf(" \n \t \t BINARY SEARCH\n \n "); printf(" Enter the size of array:" ); scanf( "%d" , &n ); printf(" \n Enter Array Elements(ascending order) :\n" ); for( i=0 ; i<n ; i++ ) scanf( "%d" , &a[i] ); printf( "\n Enter the element to be searched: " ); scanf( "%d" , &item ); printf( "\n Result of binary search:\n " ); loc = bin_search(a , 0 , n); if(loc = = 0) printf( "Unsuccessful search. %d not found.\n" , item); else { printf( " Successful search\n" ); printf( "%d found at position %d. \n" , item , loc); } printf( "The cost of running binary search is %d. \n" , cost ); getch( ); //Holds the output screen } int bin_search( int b[50] , int low , int high) { int mid , i; if(low < = high) { cost ++ ; mid = (low+high) / 2; if( item < b[mid] ) { high = mid - 1; bin_search( b , low , high); } else if( item > b[mid] ) { low = mid + 1;
bin_search( b , low , high ); } else return(mid + 1); } else return(0); } OUTPUT: BINARY SEARCH Enter the size of array:5 Enter Array Elements(ascending order) : 1 4 7 12 20 Enter the element to be searched: 12 Result of binary search: Successful search 12 found at position 4. The cost of running binary search is 3.