khalfella

ansi_c_pg054_ch03_ex01.c

Dec 27th, 2014
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. /*
  2. * Exercise 3-1.
  3. * Our binary search makes two tests inside the loop, when one would suffice
  4. * (at the price of more tests outside.) Write a version with only one test
  5. * inside the loop and measure the difference in run-time.
  6. */
  7.  
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11.  
  12.  
  13.  
  14. int
  15. bin_search(int x, int v[], int n)
  16. {
  17. int low, high, mid;
  18. low = 0;
  19. high = n - 1;
  20.  
  21. while (low < high ) {
  22.  
  23. mid = (low + high) / 2;
  24. if (x <= v[mid])
  25. high = mid;
  26. else
  27. low = mid + 1;
  28.  
  29. }
  30.  
  31. mid = (low + high) / 2;
  32. if (v[mid] == x)
  33. return mid;
  34.  
  35. return -1;
  36. }
  37.  
  38.  
  39. int
  40. binsearch(int x, int v[], int n)
  41. {
  42. int low, high, mid;
  43. low = 0;
  44. high = n - 1;
  45. while (low <= high) {
  46. mid = (low + high) / 2;
  47. if (x < v[mid])
  48. high = mid + 1;
  49. else if (x > v[mid])
  50. low = mid + 1;
  51. else
  52. return mid;
  53. }
  54.  
  55. return -1;
  56. }
  57.  
  58. int main() {
  59. int v[1000] = {0};
  60.  
  61. printf(" index = %d\n", bin_search(10,v,sizeof(v)/sizeof(int)) );
  62. printf(" index = %d\n", binsearch(10,v,sizeof(v)/sizeof(int)) );
  63. }
Advertisement
Add Comment
Please, Sign In to add comment