Binary lookup (two-point lookup)

Source: Internet
Author: User
Tags array length
Binary lookup (also known as two-point lookup)

A simple understanding is to shape an ordered array, in the search process to find the number of the middle of the array compared to the second loop to find, found the return subscript, can not find return-1.

#include < stdio.h > #include < stdlib.h>//binary lookup function int binary_search (int arr[], int key, int line)//determined array length required                            
    To pass to the function as a parameter, the length of the array cannot be computed within the function,//The array parameter is passed as a pointer to {int left = 0;
    int right = line-1; 
            while (left <= right) {int mid = left + (right-left)/2;//Array Intermediate value if (arr[mid] = = key) {
        Return mid;//found, returns subscript} else if (Arr[mid] > key) {right = Mid-1;
        else {left = mid + 1; } if (Left > right) return-1;//cannot find return-1} int main () {int arr[10] = {2, 4, 6, 8, 10, 12, 14, 1
    6, 18, 20}; int key = 100;//number to find int line = sizeof (arr)/sizeof (arr[0);//determine array length int ret = Binary_search (arr, key, line);
    Binary lookup function if (ret = 1) {printf ("not found \ n");
    else {printf ("Found:%d\n", ret); } System ("PausE ");
return 0; }

Program output results:

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.