Binary Find/binary find

Source: Internet
Author: User

Two-point lookup is also called binary lookup.

The premise: the array is ordered.

Thought: 1, each time take the middle number of key to compare, if equal, find;

2, if key > middle number, indicating that key is on the right side of the middle number, then the right side of the middle number and key comparison;

3, if key < Middle number, indicating that key is on the left side of the middle number, and then take the left of the middle number and key comparison;

4, cycle the above process;

Don't say anything, on the code:

1#include <stdio.h>2 3 intMainintargcConst Char*argv[]) {4     5     //Defining Arrays6     intArr[] = {Ten, $, the, the, -,122,456,789,999};7     8     //Find 789 subscript in this array9     intKey =789;Ten      One     intLen =sizeof(arr)/sizeof(arr[0]); A      -     intMinindex =0; -     intMaxindex = Len-1; the     intMiddleindex = len/2;//Subscript of the middle number -      -     //determine if the middle number equals key -     if(Key = =Arr[middleindex]) { +printf"The key ' s index is%d", Middleindex); -         return 0; +     } A      at     //if not equal, size is judged -      while(Key! =Arr[middleindex]) { -         if(Key < Arr[middleindex]) {//Note Key is on the left of the middle number -Maxindex = Middleindex-1;//maximum subscript to the subscript of the previous element of the intermediate number subscript -         } -         Else if(Arr[middleindex < key]) {//Note Key is on the right of the middle number inMinindex = Middleindex +1;//The minimum subscript changes to the subscript of an element after the middle number of the underlying -         } to         Else{//Description key = Arr[middleindex] +printf"The key ' s index is%d", Middleindex); -             return 0; the         } *Middleindex = (Minindex + maxindex)/2; $     }Panax Notoginseng      -printf"the number to find is not found"); the      +     return 0; A}

Binary Find/binary 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.