Example of a half-lookup in C Language

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.