Title: Counts the number of occurrences of a number in a sorted array.
For example: Sort array {1,2,3,3,3,3,4,5} and number 3, because 3 appears 4 times, so output 4
There is one of the simplest algorithms to traverse. But it's more efficient than it is.
Look at the traversal first:
#include <stdio.h> #include <assert.h>int num_time (int *arr, int len, int a) {int i = 0;int count = 0;assert (arr ! = NULL); for (; i < Len; ++i) {if (arr[i] = = a) count++;} return count;} int main () {int arr[] = {1, 2, 3, 3, 3, 3, 4, 5};int len = sizeof (arr)/sizeof (arr[0]);p rintf ("%d\n", Num_time (arr, Len, 3)); return 0;}
There is also a use of binary search:
#include <stdio.h>int getfirstkey (int arr[], int left, int. right, int len, int. key) {int mid;if (left > right) {RET urn-1;} Mid = left-(left-right)/2;if (key = Arr[mid]) {if (Mid > 0 && arr[mid-1]! = key) | | mid = = 0) {return m ID;} Else{right = Mid-1;}} else if (Arr[mid] < key) {left = mid + 1;} Else{right = mid-1;} Return Getfirstkey (arr, left, right, Len, key);} int Getlastkey (int arr[], int left, int. right, int len, int. key) {int mid;if (left > right) {return-1;} Mid = left-(left-right)/2;if (key = Arr[mid]) {if (Mid < len-1 && Arr[mid + 1]! = Key | | mid = len- 1) {return mid;} Else{left = mid + 1;}} else if (Arr[mid] < key) {left = mid + 1;} Else{right = mid-1;} Return Getlastkey (arr, left, right, Len, key);} int main () {int brr[] = {1, 2, 3, 3, 3, 3, 4, 5};int len = sizeof (BRR)/sizeof (brr[0]); int first = Getfirstkey (BRR, 0, L En-1, len-1, 3); int last = Getlastkey (brr, 0, Len-1, len-1, 3);p rintf ("%d\n", Last-first + 1); retUrn 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"C Language" counts the number of occurrences of a number in a sorted array