Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to find the nearest smaller element on left side of each element of an array in C++

1 Answer

0 votes
#include <iostream>
 
int smaller_index(int arr[], int pos) {
    int index = -1;
  
    for (int i = pos - 1; i >= 0 && index==-1; i--) {
        if (arr[i] < arr[pos]) {
            index = i;
        }
    }
    return index;
}
void nearest_smaller(int arr[], int size) {
    int index = 0;
  
    for (int i = 0; i < size; i++) {
        index = smaller_index(arr, i);
  
        if (index == -1) {
            std::cout << arr[i] << " : No Smaller\n";
        }
        else  {
            std::cout << arr[i] << ": " << arr[index] << "\n";
        }
    }
}
  
int main()
{
  int arr[] = {4, 6, 2, 8, 6, 1, 9, 12, 3, 20, 18, 30};
  
  int size = sizeof(arr) / sizeof(arr[0]);
  
  nearest_smaller(arr, size);
    
  return 0;
}
  
  
  
  
/*
run:
  
4 : No Smaller
6: 4
2 : No Smaller
8: 2
6: 2
1 : No Smaller
9: 1
12: 9
3: 1
20: 3
18: 3
30: 18
  
*/

 



answered Dec 19, 2021 by avibootz
edited Dec 19, 2021 by avibootz
...