• Source
    1. #include <stdio.h>
    2.  
    3. int main()
    4. {
    5. int arr[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
    6. int first, last, start, end, mid, x;
    7.  
    8. scanf("%d", &x);
    9.  
    10. start = 0;
    11. end = 9;
    12. first = last = -1;
    13. while (start <= end) {
    14. mid = start + (end - start) / 2;
    15. if (arr[mid] == x) {
    16. first = mid;
    17. end = mid - 1;
    18. } else if (arr[mid] <= x) {
    19. start = mid + 1;
    20. } else {
    21. end = mid - 1;
    22. }
    23. }
    24.  
    25. start = 0;
    26. end = 9;
    27. while (start <= end) {
    28. mid = start + (end - start) / 2;
    29. if (arr[mid] == x) {
    30. last = mid;
    31. start = mid + 1;
    32. } else if (arr[mid] < x){
    33. start = mid + 1;
    34. } else {
    35. end = mid - 1;
    36. }
    37. }
    38.  
    39.  
    40. if (last != -1)
    41. printf("The number of occurance is %d\n", last - first + 1);
    42. else
    43. printf("The number of occurance is 0\n");
    44. return 0;
    45. }