Binary search

Hello,

I`m doing the exercises of the C programming language and the question is as follows:

Our binary search makes two tests inside the loop, when one would suffice (at the price of more tests outside). Write a version with only one test inside the loop and measure the difference in run-time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

#include <stdio.h>

/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */




int binsearch(int x, int v[], int n) {
    int low, mid, high;
    
    low = 0;
    high = n - 1;
    while ( low <= high ) {
        mid = (low+high) / 2;
        if ( x < v[mid] )
            high = mid - 1;
        else if ( x > v[mid] )
            low = mid + 1;
        else
            return mid;
    }
    return -1;
}



/* Improved version */

int binsearch2(int x, int v[], int n)

{
  int low, high, mid;
  low = 0;
  high = n-1;
  
  while (low <= high) {
   mid = (low + high) / 2;
   if (x < v[mid])
      high = mid-1;
   else
      low = mid+1;
  }
    
 return x == v[mid] ? mid : -1;
 
}
  
  
int main(int argc, char *argv[])

{
  
unsigned index; 
int n = 10;                                                       /* Element to search for */
int Array[] = { 2, 4, 6, 8, 10, 12, 14 };

for (index = 0; index < sizeof(Array); index++)
 {

int answer = binsearch2( n, Array, sizeof(Array) / sizeof(int) );

printf("%d", answer);

  }

}




Am I doing this right? At the moment I get this output:
4444444444444444444444444444
What's the purpose of lines 58,59,65? If you comment those out, the output is 4 (the index of "10" in the Array). You get 28 times 4 because the size of Array is 28 (7*4 bytes). You are suppose to time the two methods. I would skip timing the print statement
Topic archived. No new replies allowed.