First look at the program:
#include <stdio.h> #include <assert.h> int binary_search (int x, int v[], int n) {int high, low, mid; low = 0; High = n-1; MID = 0; while (low <= high) {mid = (low + high)/2, if (x < V[mid])/*SEARVH the left half*/high = mid + 1; else if (x > V [mid])/*search the right half*/low = mid + 1; else return mid; } return-1; /*not match*/} int main () {int i; int array[10]; int val; int result = one; for (i = 0; i <; ++i) {Array[i] = i * 2 + 1; printf ("%d", Array[i]);} printf ("Input value want to compare to the array:"); scanf ("%d", &val); result = Binary_search (val, array, 10); for (i = 0; i < ++i) {//array[i] = i * 2 + 1; printf ("%d", Array[i]);} if ( -1 = = Result | | result >=) printf ("/nnot found!/n"); else printf ("/nthe position in the array is%d/n", result); return 0; }
When the value of the read-in Val is an even number like 4 o'clock, the program enters the dead loop, the key points in
if (x < V[mid])/*SEARVH the left half*/high = mid + 1;
should be high = mid-1;
#include <stdio.h> #include <assert.h> int binary_search (int x, int v[], int n) {int high, low, mid; low = 0; High = n-1; MID = 0; while (low <= high) {mid = (low + high)/2, if (x < V[mid])/*SEARVH the left half*/high = mid-1; else if (x > V [mid])/*search the right half*/low = mid + 1; else return mid; } return-1; /*not match*/} int main () {int i; int array[10]; int val; int result = one; for (i = 0; i <; ++i) {Array[i] = i * 2 + 1; printf ("%d", Array[i]);} printf ("Input value want to compare to the array:"); scanf ("%d", &val); result = Binary_search (val, array, 10); for (i = 0; i < ++i) {//array[i] = i * 2 + 1; printf ("%d", Array[i]);} if ( -1 = = Result | | result >=) printf ("/nnot found!/n"); else printf ("/nthe position in the array is%d/n", result); return 0; }
But
Mid = (low + high)/2
is still a bug, because the Low+high out of the positive range of int will become negative, then the mid is also wrong, and the back with the array elements in the mid is not natural. Can be changed into:
int mid = low + ((high-low)/2);