This code implements binary search on an array of integers. It first sorts the array, then repeatedly selects the midpoint of the current search range and compares the target value to the element at the midpoint. If equal, it exits with success. Otherwise it narrows the range based on whether the target is lower or higher than the midpoint element.
This code implements binary search on an array of integers. It first sorts the array, then repeatedly selects the midpoint of the current search range and compares the target value to the element at the midpoint. If equal, it exits with success. Otherwise it narrows the range based on whether the target is lower or higher than the midpoint element.
Copyright:
Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online from Scribd
This code implements binary search on an array of integers. It first sorts the array, then repeatedly selects the midpoint of the current search range and compares the target value to the element at the midpoint. If equal, it exits with success. Otherwise it narrows the range based on whether the target is lower or higher than the midpoint element.
Copyright:
Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online from Scribd
#inc lude<con io .h> vo id main ( ) { i n t f l ag=0 ,a [20 ] ,n ,pos , i , i t em, low ,h igh ,m id ; vo id so r t ( i n t [ ] , i n t ) ; c l r sc r ( ) ; pr in t f ( " \nEn te r the no . o f number : \ t " ) ; scan f ( "%d" ,&n) ; pr in t f ( " \nEn te r the numbers \n " ) ; f o r ( i=1 ; i<=n; i++) scan f ( "%d" ,&a[ i ] ) ; so r t (a ,n ) ; pr in t f ( " \nEn te r the data to be sea rched : \n " ) ; scan f ( "%d" ,& i tem) ; l ow=1; h igh=n; whi le ( l ow<=h igh ) { mid=( low+h igh ) /2 ; i f ( i t em==a[mid ] ) { f l ag=1; break ; } e l se i f ( i t em>a[mid ] ) l ow=mid+1; e l se h igh=mid - 1 ; } i f ( f l ag==0) pr in t f ( " \nThe e lement %d i s not presen t i n the ar ray \n" , i t em) ; e l se pr in t f ( "The e lement %d i s presen t i n the ar ray" , i t em) ; getch ( ) ; } vo id so r t ( i n t a[ ] , i n t n) { i n t i , j , t emp; f o r ( i=1 ; i<=n-1 ; i++) f o r ( j= i+1 ; j<=n; j++) i f ( a [ i ]>a [ j ] ) { temp=a[ i ] ; a[ i ]=a[ j ] ; a[ j ]=temp; } }