i want to construct my code for solving All nearest smaller values problem,here is my effort for this
#include<iostream>
#include<stack>
using namespace std;
void all_smallest(int a[],int n)
{
stack<int>s;
for(int x=0;x<n;x++)
{
while(!s.empty() && s.top()>=a[x])
{
cout<<s.top();
s.pop();
}
if(s.empty()){ continue;}
else
{
s.push(a[x]);
}
}
}
int main()
{
int a[]={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
int n=sizeof(a)/sizeof(a[0]);
all_smallest(a,n);
return 0;
}
it compiles,but no output ,why?please help me
Checking Wikipedia you didn't implement the algorithm correctly. Here's what it should be:
#include<iostream>
#include<stack>
using namespace std;
void all_smallest(int a[],int n)
{
stack<int>s;
for(int x=0;x<n;x++)
{
while(!s.empty() && s.top()>=a[x])
{
s.pop();
}
if(!s.empty())
{
cout<<s.top();
}
s.push(a[x]);
}
}
int main()
{
int a[]={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
int n=sizeof(a)/sizeof(a[0]);
all_smallest(a,n);
cout << "\n";
return 0;
}
Output:
004022601151337