Find algorithm--two points to find

Source: Internet
Author: User

One, C program implementation

/********************************************************************************************description two-part search algorithm *author liaoxiongxiong*version 1.0*time 2018-04-28*************************************************************** /#include <stdio.h>//binary lookup, version 1int BinarySearch1 (int a[], int value, int n) {int low, H    IgH, Mid;    Low = 0;    High = n-1;        while (Low<=high) {mid = (Low+high)/2;        if (a[mid] = = value) return mid;        if (a[mid]>value) high = mid-1;    if (a[mid]<value) low = mid+1; } return-1;}    Binary lookup, version 2, recursive version int BinarySearch2 (int a[], int value, int low, int. high) {int mid = low+ (high-low)/2;    if (A[mid]==value) return mid;    if (A[mid]>value) return BinarySearch2 (A, value, low, mid-1); if (A[mid]<value) return BinarySearch2 (A, value, mid+1, high);}    Test Case int Main () {int a[]={0,1,2,3,4,5,6,7,8,9};    int len = sizeof (a)/sizeof (a[0]); int x= 2;    The element that needs to be looked up int i = BINARYSEARCH2 (A, x, 0, Len);    if (i!=-1) printf ("element%d at%d position \ n", x,i+1);    else printf ("element not found:%d\n", X); return 0;}

Operation Result:

Find algorithm--two points to find

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.