fork download
  1. import java.util.*;
  2.  
  3. class FindFirstOne {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6.  
  7. // Input size of the array
  8. System.out.print("Enter the size of the array: ");
  9. int n = sc.nextInt();
  10.  
  11. // Input elements of the array
  12. int[] arr = new int[n];
  13. System.out.println("Enter the elements (0s and 1s only): ");
  14. for (int i = 0; i < n; i++) {
  15. arr[i] = sc.nextInt();
  16. }
  17.  
  18. int firstOccurrence = findFirstOne(arr, n);
  19.  
  20. if (firstOccurrence != -1) {
  21. System.out.println("First occurrence of 1 is at index: " + firstOccurrence);
  22. } else {
  23. System.out.println("1 is not present in the array.");
  24. }
  25. }
  26.  
  27. public static int findFirstOne(int[] arr, int n) {
  28. int start = 0;
  29. int end = n - 1;
  30. int maybeFirst1 = -1;
  31.  
  32. while (start <= end) {
  33. int mid = start + (end - start) / 2; // Correctly calculate mid
  34.  
  35. if (arr[mid] == 0) {
  36. start = mid + 1; // Move right if 0 is found
  37. } else {
  38. maybeFirst1 = mid; // Found a 1, keep track
  39. end = mid - 1; // Move left to find the first occurrence
  40. }
  41. }
  42.  
  43. return maybeFirst1; // Return the index of the first occurrence of 1
  44. }
  45. }
  46.  
Success #stdin #stdout 0.15s 58912KB
stdin
5
0 0 1 1 1
stdout
Enter the size of the array: Enter the elements (0s and 1s only): 
First occurrence of 1 is at index: 2