Skip to content

Commit 371b3bd

Browse files
committed
minor tweaks
1 parent 4becd4a commit 371b3bd

File tree

1 file changed

+14
-30
lines changed

1 file changed

+14
-30
lines changed

chapter03/3-1.c

+14-30
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,21 @@
33
* would suffice (at the price of more tests outside.) Write a version with
44
* only one test inside the loop and measure the difference in run-time.
55
*
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.
96
* By Faisal Saadatmand
107
*/
118

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+
1215
#include <stdio.h>
1316

1417
#define SIZE 12
1518

1619
/* functions */
1720
int binSearch(int, int [], int);
18-
int binSearch_alt(int, int [], int);
1921

2022
/* binSearch: find x in value[0] <= value[1] <= ... <= value[n - 1] */
2123
int binSearch(int x, int v[], int n)
@@ -24,26 +26,6 @@ int binSearch(int x, int v[], int n)
2426

2527
low = 0;
2628
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-
4729
while (low < high) {
4830
mid = (low + high) / 2;
4931
if (v[mid] < x)
@@ -52,19 +34,21 @@ int binSearch_alt(int x, int v[], int n)
5234
high = mid;
5335
}
5436
if (v[low] == x)
55-
return low;
56-
return -1;
37+
return low; /* found match */
38+
return -1; /* no match */
5739
}
5840

5941
int main(void)
6042
{
6143
int array[SIZE] = { 2, 4, 5, 6, 8, 9, 12, 16, 20, 32, 40, 78 };
62-
int number = 0;
44+
int input, number;
6345

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) {
6747
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));
6852
}
6953
return 0;
7054
}

0 commit comments

Comments
 (0)