"C Language" counts the number of occurrences of a number in a sorted array

Source: Internet
Author: User

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

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.