Binary Search and trigger search algorithm C #

Source: Internet
Author: User

The first is the binary search method, time complexity O (2log2 (N )):

Static bool find (INT [] sortedarray, int number)
{
If (sortedarray. Length = 0)
Return false;

Int start = 0;
Int end = sortedarray. Length-1;

While (end> = start)
{
Int middle = (start + end)/2;
If (sortedarray [Middle] <number)
Start = middle + 1;
Else if (sortedarray [Middle]> Number)
End = middle-1;
Else
Return true;
}
Return false;
}

Then there is a three-point search algorithm, time complexity O (3log3 (N )):

Static bool find (INT [] sortedarray, int number)
{
If (sortedarray. Length = 0)
Return false;

Int start = 0;
Int end = sortedarray. Length-1;

While (end> = start)
{
Int firstmiddle = (end-Start)/3 + start;
Int secondmiddle = end-(end-Start)/3;
If (sortedarray [firstmiddle]> Number)
End = firstmiddle-1;
Else if (sortedarray [secondmiddle] <number)
Start = secondmiddle + 1;
Else if (sortedarray [firstmiddle]! = Number & sortedarray [secondmiddle]! = Number)
{
End = secondmiddle-1;
Start = firstmiddle + 1;
}
Else
Return true;
}
Return false;
}

Comparison shows that the time complexity of the three-part search algorithm is lower than that of the binary search algorithm, but the efficiency is not as high as that of the binary search algorithm, therefore, we cannot be too superstitious about the time complexity of an algorithm.

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.