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