0% found this document useful (0 votes)
13 views

Bin Search

This document contains C code for implementing binary search and a function to estimate the number of comparisons needed for sorting using binary search. It includes function definitions for binary search, binary search recursion, and a function that uses binary search and logarithms to estimate the number of comparisons. It also contains main() code to test the binary search and sorting estimate functions.

Uploaded by

algoguru
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Bin Search

This document contains C code for implementing binary search and a function to estimate the number of comparisons needed for sorting using binary search. It includes function definitions for binary search, binary search recursion, and a function that uses binary search and logarithms to estimate the number of comparisons. It also contains main() code to test the binary search and sorting estimate functions.

Uploaded by

algoguru
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

C:\Users\prashantr4\Desktop\binsearch.c #include<stdio.h> #include<stdlib.h> #include<limits.h> #include<math.

h> int BinSearch(int arr[],int lo,int hi,int key){ int pos; while(lo<=hi){ pos=(lo+hi)/2; if(arr[pos]>key){ hi=pos-1; } else if(arr[pos]<key){ lo=pos+1; } else{ return pos; } } return -1; } int BinSearchRec(int arr[],int lo,int hi,int key){ int pos=(lo+hi)/2; if(hi<lo){ return -1; } if(arr[pos] > key){ printf("Key Small: %d\n",arr[pos]); return BinSearchRec(arr,lo,pos-1,key); } else if(arr[pos] < key){ printf("Key Big: %d\n",arr[pos]); return BinSearchRec(arr,pos+1,hi,key); } else{ printf("Key Found: %d\n",arr[pos]); return pos; } }

// TopCoder Prob SortEstimate: http://community.topcoder.com/stat?c=problem_statement& pm=3561&rd=6519 double howMany(int c, int time){ double eq=time; double minVal=0.0; double maxVal=eq; double err=1e-9,eVal; double midVal; printf("Eq: %lf\n",eq); while(1){ // printf("%lf %lf\n",minVal,maxVal); midVal=(minVal+maxVal)/2; eVal=(c*midVal*log2(midVal))-eq; printf("%lf %lf\n",midVal,eVal); if(eVal>0.0){ maxVal=midVal; } else if(eVal<=0.0){ if(abs(eVal)<err){ printf("midVal: %lf\n",midVal); return midVal; }

//

//

C:\Users\prashantr4\Desktop\binsearch.c else{ minVal=midVal; } } } } int main(void){ int arr[]={0,1,3,4,5,6,7,8,9,10}; int x; double hm; //x=BinSearch(arr,0,(sizeof(arr)/sizeof(int))-1,7); //printf("Pos: %d\n",x); hm=howMany(1,8); printf("N: %lf\n",hm); hm=howMany(2,16); printf("N: %lf\n",hm); hm=howMany(37,12392342); printf("N: %lf\n",hm); hm=howMany(1,2000000000); printf("N: %lf\n",hm); system("pause"); }

You might also like