(algorithm: Binary lookup) in a sorted array, to find out the number of occurrences of a given number

Source: Internet
Author: User

Topic:

In the sorted array, find out the number of occurrences of a given number

Ideas:

Since there is a sort array, it is easy to think of binary lookups, with time complexity O (LOGN);

First, by binary find the leftmost occurrence of the number of the subscript left (if not found, then return-1), and then through the binary search find the rightmost occurrence of the number of the following table right (if not found, then return-1), and then right-left+1 is the number of occurrences;

Code:
#include <iostream>using namespace Std;int binarysearchcount (int *array,int len,int data) {if (len<1) return-1    ;    int left=0;    int right=len-1;    int mid;    int leftindex=-1;        Find the left index while (left<=right) {mid=left+ ((right-left) >>1);            if (array[mid]==data) {leftindex=mid;        Right=mid-1;        } else if (array[mid]<data) left=mid+1;    else right=mid-1;    }//Find the right index left=0;    right=len-1;    int rightindex=-1;        while (left<=right) {mid=left+ ((right-left) >>1);            if (array[mid]==data) {rightindex=mid;        left=mid+1;        } else if (array[mid]<data) left=mid+1;    else right=mid-1;    } if (Leftindex!=-1 && rightindex!=-1) return rightindex-leftindex+1; else return 0;}    int main () {int arr[]={0,1,2,3,3,3,3,3,3,3,4,5,6,7,13,19}; int len=sizeof (arr)/sizEOF (Arr[0]);    cout << Binarysearchcount (arr,len,18) << Endl; return 0;}

(algorithm: Binary lookup) in a sorted array, to find out the number of occurrences of a given number

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.