Common Binary Search

Source: Internet
Author: User

This is an extremely simple algorithm. It is precisely because of its simplicity that I often get killed by it. I followed suit either during the competition or during the interview. Because of its simplicity, I don't want to spend too much time writing it. I always want to write it in one breath, but it doesn't work either. So my head is getting more and more chaotic, and my mood is getting more and more excited. As a result, the tragedy comes along.

Binary Search requires that the queried array be an ordered array, and its time complexity is O (log (N). That is to say, 0.1 billion of the data volume can be obtained after it is run for about 26 times.

# Include <stdio. h> # include <stdlib. h> int B _search (void * arr, int N, INT (* CMP) (void *, void *), void * Key, int size) {int left = 0, right = n-1, mid = 0; while (left <= right) {mid = (left + right)/2; If (CMP (Key, (char *) arr + mid * size) = 0) return mid; else if (CMP (Key, (char *) Arr + mid * size) <0) Right = mid-1; else left = Mid + 1;} return-1 ;}

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.