How to find the first smaller number to the left element for each array element in Java

1 Answer

0 votes
public class MyClass {
    public static void findFirstSmallerNumberToTheLeft(int arr[]) {
        int size = arr.length;
        for (int i = 0; i < size; i++) {
            int first_smaller_number_to_the_left = -1; // if not found write -1
      
            for (int j = i - 1; j >= 0; j--) {
                if (arr[j] < arr[i]) {
                    first_smaller_number_to_the_left = arr[j];
                    break;
                }
            }
      
            System.out.print(first_smaller_number_to_the_left + " ");
        }
    }
    public static void main(String args[]) {
        int arr[] = { 2, 6, 3, 7, 8, 1, 9, 0, 13, 19, 18 };
     
        // 2:-1 // 6:2 // 3:2 // 7:3 // 8:7 // 1:-1 // 9:1 // 0:-1 // 13:0 // 19:13 // 18:13
  
        findFirstSmallerNumberToTheLeft(arr);
    }
}




/*
run:
 
-1 2 2 3 7 -1 1 -1 0 13 13 
 
*/

 



answered Nov 25, 2021 by avibootz
...