fork download
  1. // Write a Program to take a sorted array arr[] and an integer x as input, find the index (0-based) of the smallest element in arr[] that is greater than or equal to x and print it. This element is called the ceil of x. If such an element does not exist, print -1. Note: In case of multiple occurrences of ceil of x, return the index of the first occurrence.
  2.  
  3. #include <stdio.h>
  4.  
  5. int main() {
  6. int n, x;
  7. scanf("%d", &n);
  8.  
  9. int arr[n];
  10. for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
  11.  
  12. scanf("%d", &x);
  13.  
  14. int low = 0, high = n - 1, ans = -1;
  15.  
  16. while (low <= high) {
  17. int mid = (low + high) / 2;
  18.  
  19. if (arr[mid] >= x) {
  20. ans = mid; // possible ceil
  21. high = mid - 1; // move left for first occurrence
  22. } else {
  23. low = mid + 1;
  24. }
  25. }
  26.  
  27. printf("%d", ans);
  28. return 0;
  29. }
  30.  
  31.  
  32.  
Success #stdin #stdout 0s 5312KB
stdin
6
2 3 5 7 7 9
7

stdout
3