Algorithm Learning One ~ division of the Law ~ two points to find, fast to find ~

Source: Internet
Author: User

Now programming is also to walk the door, but did not grasp the algorithm can only say that they are still laymen, so we began to work hard to learn the algorithm, now put their daily learning to share in here hope everyone can like, and I also want to organize my day of study and thinking,.

Two-point lookup: You often need to look for a value in an array. If it's a good order then you can find it quickly. We consider the brute force search, that is a "n", find a M, then the best is O (1), the worst is 0 (N), the final average is the length of N/2. Such time complexity is not very high but can be improved to the level of Logn.
1#include <stdio.h>//algorithm Two-point search2 intMain ()3 {4 inta[100000],i,x;5  while(~SCANF ("%d",&x))6 {7  for(i=0;i<100000; i++)//assign a value to an array. It's going to be a good order.8a[i]=i;9 intleft=0, right=i-1;//Left/Right value =iTen intmiddle=0; One  while(Left<=right)//when the algorithm is in the left small less right operand A { -Middle= (left+right)/2;//start looking in the middle . -     if(X==a[middle]) Break;//end Loop already found the     if(X>a[middle]) left=middle+1;//cut it down in half every time -     Elseright=middle-1; - } -printf"%d\n", middle);//Output + } -}

The idea here is simple to judge whether the middle element is the element to be found, then the size if x is smaller than the median value in the left-to-middle value, if larger than the median value and the right to start judging. And then there is the constant cycle of course, which can also be recursive. The problem is simple, and I'm not going to say much nonsense. ,。。

Algorithm Learning One ~ division of the Law ~ two points to find, fast 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.