fork download
  1. #include <stdio.h>
  2.  
  3. // Function to find smallest missing element in a sorted
  4. // array of distinct non-negative integers
  5. int smallestMissing(int arr[], int low, int high)
  6. {
  7. // base condition
  8. if (low > high)
  9. return low;
  10.  
  11. int mid = low + (high - low) / 2;
  12.  
  13. // if mid index matches with the mid element, then the mismatch
  14. // lies on the right half
  15. if (arr[mid] == mid)
  16. return smallestMissing(arr, mid + 1, high);
  17. else
  18. // mismatch lies on the left half
  19. return smallestMissing(arr, low, mid - 1);
  20. }
  21.  
  22. // main function
  23. int main(void)
  24. {
  25. int arr[] = { 0, 1, 2, 3, 4, 5, 6 };
  26. int n = sizeof(arr) / sizeof(arr[0]);
  27.  
  28. int low = 0, high = n - 1;
  29.  
  30. printf("The smallest missing element is %d",
  31. smallestMissing(arr, low, high));
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 4536KB
stdin
Standard input is empty
stdout
The smallest missing element is 7