Two points find __ two points search

Source: Internet
Author: User

Of all the search algorithms, the binary lookup is the simplest one. The binary lookup requires that the original sequence be sorted, each time as compared to the number in the middle of the sequence, and if less than the middle number, then continue the recursive lookup on the left side of the sequence, if greater than the middle number, then continue the recursive lookup on the right side of the sequence. The lookup fails until the number is found, or until there is only one number in the sequence that is not found. The time complexity of the lookup can be achieved O (LOGN), which should be the quickest way to find an O (1), except for an array by subscript. Sample code uploaded to Https://github.com/chenyufeng1991/BinarySearch.

Using the C language complete implementation is as follows:

Implement a binary lookup
#include <stdio.h>
#include <stdlib.h>

void binarysearch (int *arr, int start, int end , int num);

int main (int argc, const char * argv[])
{
    int array[] = {4,5,6,7,8,9};

    BinarySearch (Array, 0, 5,);

    return 0;
}

void BinarySearch (int *arr, int start, int end, int num)
{
    int mid = (start + end)/2;
    if (arr[mid] = num)
    {
        printf ("%d", mid);
        return;
    }

    if (start = = end)
    {
        printf ("not Found");
        return;
    }

    if (num < Arr[mid])
    {
        BinarySearch (arr, start, Mid, num);
    }

    if (num > Arr[mid])
    {
        BinarySearch (arr, mid + 1, end, num);
    }

    return;
}


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.