3
3
* would suffice (at the price of more tests outside.) Write a version with
4
4
* only one test inside the loop and measure the difference in run-time.
5
5
*
6
- * Answer: binSearch_alt algorithm is faster because it has one less
7
- * comparison in the loop; However it doesn't stop when the number is found in
8
- * the loop.
9
6
* By Faisal Saadatmand
10
7
*/
11
8
9
+ /*
10
+ * Answer: this version is faster because it has one less comparison in the
11
+ * loop; However, it doesn't stop the loop as soon as the match is found.
12
+ * the loop.
13
+ */
14
+
12
15
#include <stdio.h>
13
16
14
17
#define SIZE 12
15
18
16
19
/* functions */
17
20
int binSearch (int , int [], int );
18
- int binSearch_alt (int , int [], int );
19
21
20
22
/* binSearch: find x in value[0] <= value[1] <= ... <= value[n - 1] */
21
23
int binSearch (int x , int v [], int n )
@@ -24,26 +26,6 @@ int binSearch(int x, int v[], int n)
24
26
25
27
low = 0 ;
26
28
high = n - 1 ;
27
-
28
- while (low <= high ) {
29
- mid = (low + high ) / 2 ;
30
- if (x < v [mid ])
31
- high = mid - 1 ;
32
- else if (x > v [mid ])
33
- low = mid + 1 ;
34
- else
35
- return mid ; /* match found */
36
- }
37
- return -1 ; /* no match */
38
- }
39
-
40
- int binSearch_alt (int x , int v [], int n )
41
- {
42
- int low , high , mid ;
43
-
44
- low = 0 ;
45
- high = n - 1 ;
46
-
47
29
while (low < high ) {
48
30
mid = (low + high ) / 2 ;
49
31
if (v [mid ] < x )
@@ -52,19 +34,21 @@ int binSearch_alt(int x, int v[], int n)
52
34
high = mid ;
53
35
}
54
36
if (v [low ] == x )
55
- return low ;
56
- return -1 ;
37
+ return low ; /* found match */
38
+ return -1 ; /* no match */
57
39
}
58
40
59
41
int main (void )
60
42
{
61
43
int array [SIZE ] = { 2 , 4 , 5 , 6 , 8 , 9 , 12 , 16 , 20 , 32 , 40 , 78 };
62
- int number = 0 ;
44
+ int input , number ;
63
45
64
- printf ("Enter number to search in the array: " );
65
- while (scanf ("%i" , & number ) != EOF ) {
66
- printf ("%i\n" , binSearch_alt (number , array , SIZE ));
46
+ while (1 ) {
67
47
printf ("Enter number to search in the array: " );
48
+ input = scanf ("%i" , & number );
49
+ if (!input || input == EOF )
50
+ return -1 ;
51
+ printf ("%i\n" , binSearch (number , array , SIZE ));
68
52
}
69
53
return 0 ;
70
54
}
0 commit comments