Repository containing solution for #SdeSheetChallenge by striver
Insert function.
x
is the largest element, then we can directly insert it at last position.x
at it’s correct position.x
recursively.Sort function.
#include <bits/stdc++.h>
void insertSorted(stack<int>& st, int x) {
if (st.empty() || st.top() <= x) {
st.push(x);
} else {
int temp = st.top();
st.pop();
insertSorted(st, x);
st.push(temp);
}
}
void sortStack(stack<int>& stack)
{
if (stack.empty())
return;
int x = stack.top();
stack.pop();
sortStack(stack);
insertSorted(stack, x);
}