There is an array v in ascending order, and array v has n = 20 elements. The array has an element x. How do I know the number of digits in the array?
A common solution to this problem is half-lookup. The following is a program:
# Include <stdio. h> int binsearch (int x, int v [], int n); main () {int I, result, n; int wait; int x = 17; // int v [19]; // defines an array // assign a value to the array for (I = 0; I <20; ++ I) v [I] = I;/** for (I = 0; I <20; ++ I) printf ("% d \ n", v [I]); */n = 20; result = binsearch (x, v, n); printf ("% d", result); scanf ("% d", & wait );} 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-1; else if (x> v [mid]) low = mid + 1; elsereturn mid; // check the number of printf ("mid = % d, low = % d, high = % d \ n", mid, low, high);} return-1 ;}
The idea is simple: first, compare the input value x with the intermediate element of array v. If x is smaller than the intermediate element, set the high value to the intermediate element-1. Similarly, if x is greater than the intermediate element, the intermediate element + 1 is used as the low, and then the low and high are searched.