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

1 Answer

0 votes
#include <iostream>

void findFirstSmallerNumberToTheLeft(int arr[], int size) {
    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;
            }
        }
  
        std::cout << first_smaller_number_to_the_left << " ";
    }
}
  
int main(void)
{
    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, sizeof(arr) / sizeof(arr[0]));
  
    return 0;
}
 
 
 
 
 
/*
run:
 
-1 2 2 3 7 -1 1 -1 0 13 13 
 
*/

 



answered Nov 25, 2021 by avibootz
...