Welcome to collectivesolver - Programming & Software Q&A with Examples. A website you can trust. All programs tested and work.

Contact: aviboots(AT)netvision.net.il


Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Survey Junkie is the #1 place online for your audience to earn rewards for their opinion.

100%
Managed VPS Hosting
Affordable. Secure. Your Own Virtual Private Hosting. Faster than AWS and Rackspace

Bonsai Boy of New York Bonsai Trees and Accessories
Liquid Web - Highest Level of Performance and Security with Managed Dedicated Servers

Disclosure We are a professional Programming & Software Q&A website, that receives compensation from some of the links whose we show you with Information. It means that my content may contain affiliate links.

20,687 questions

27,328 answers

573 users

How to find the previous smaller element from the beginning of array for each array element in C++

1 Answer

0 votes
#include <iostream>

void findPreviousSmaller(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        int not_found = 1; // if not found write -1
   
        int previous_smaller = arr[i];
        for (int j = i - 1; j >= 0; j--) {
            if (arr[j] < previous_smaller) {
                previous_smaller = arr[j];
                not_found = 0;
            }
        }
   
        std::cout << ((not_found) ? -1 : previous_smaller) << " ";
    }
}
   
int main(void)
{
    int arr[] = { 2, 6, 3, 7, 8, 1, 9, 0, 13, 19, 18 };
      
    // 2:-1 // 6:2 // 3:2 // 7:2 // 8:2 // 1:-1 // 9:1 // 0:-1 // 13:0 // 19:0 // 18:0
   
    findPreviousSmaller(arr, sizeof(arr) / sizeof(arr[0]));
   
    return 0;
}
  
 
  
  
/*
run:
 
-1 2 2 2 2 -1 1 -1 0 0 0 
 
*/

 




answered Nov 25 by avibootz
...