summaryrefslogtreecommitdiff
path: root/ch3
diff options
context:
space:
mode:
authorAdam Carpenter <gitlab@53hor.net>2019-07-23 13:43:29 -0400
committerAdam Carpenter <gitlab@53hor.net>2019-07-23 13:43:29 -0400
commit3e4c2b79987a583d4ac00192eb6ac0cfb3b53997 (patch)
treeb7029127549383d1e1b090e47fd216d51443a187 /ch3
parentcbfba32803a16ebe6b33f8ccdedf602cc49addc7 (diff)
downloadlearning-c-master.tar.xz
learning-c-master.zip
Finished 3-1.HEADmaster
Diffstat (limited to 'ch3')
-rw-r--r--ch3/3-1.c50
1 files changed, 50 insertions, 0 deletions
diff --git a/ch3/3-1.c b/ch3/3-1.c
new file mode 100644
index 0000000..0dea28e
--- /dev/null
+++ b/ch3/3-1.c
@@ -0,0 +1,50 @@
+#include <stdio.h>
+
+int binsearch(int x, int v[], int n);
+int binsearch_original(int x, int v[], int n);
+
+int main() {
+ int v[] = {1,2,3,4,5};
+ int x = 2;
+ int n = 5;
+ printf("%d\n%d\n", binsearch_original(x, v, n), binsearch(x, v, n));
+}
+
+int binsearch(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;
+ else
+ low = mid + 1;
+ }
+
+ return (x == v[low]) ? low : -1;
+}
+
+/*
+ * Find x in v[0] <= v[1] <= ... <= v[n-1]
+ */
+int binsearch_original(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 if (x > v[mid])
+ low = mid + 1;
+ else // found match
+ return mid;
+ }
+
+ return -1; // no match
+}