How to give the number of occurrences of a specified number in an ordered array

Source: Internet
Author: User

Problem Description: How many occurrences of a specified number are given in an ordered array, for example: array {1,2,2,2,3,4,5} number 2 has a number of occurrences of 3.

The simplest way is to iterate through the array, with the following code:

#include <stdio.h>//How to give the number of occurrences of a specified number in an ordered array int binarysearch (int *a,int n,int x) {int cnt=0;for (int i=0;i<n;i++) { if (a[i]==x) cnt++;} return CNT;} int main () {int a[10]={1,2,3,4,5,6,6,6,9,10};p rintf ("%d\n", BinarySearch (a,10,6)); return 0;}

Here I think you can use the array order to optimize the number of comparisons, I hope you discuss, the topic source of a well-known Internet company internship surface questions.

The code is as follows:

#include <stdio.h>//How to give the number of occurrences of a given number in an ordered array int binarysearch (int *a,int low,int high,int x) {int Cnt=0;int temp;int mid = (Low+high)/2;while (Low<=high) {mid= (Low+high)/2;if (a[mid]<x) Low=mid+1;else if (a[mid]>x) high=mid-1;else {temp=mid;//program runs to this element x already appears once Cnt++;while (A[++mid]==x) cnt++;while (a[--temp]==x) Cnt++;return cnt;}} Lookup failed, return 0return 0;} int main () {int a[10]={1,2,3,4,5,6,6,6,9,10};p rintf ("%d\n", BinarySearch (a,0,10,6)); return 0;}


Ideas:

The first two points find the corresponding element, if the search fails to return 0, if the search succeeds, record the current position, to the sides of the judgment, the program structure, although it seems more complex, if the array size, efficiency has a lot of improvement, hope that a better way of friends can advise.

How to give the number of occurrences of a specified number in an ordered array

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.