Sort a stack of integers in ascending order.

Given a stack of integers, this algorithm will sort the stack in ascending order. Additional stacks may be used to hold the elements, but no other data structures are allowed.

Problem

Given a stack of integers, sort the stack in ascending order. You may use additional stacks to hold the elements, but you may not use any other data structures (arrays, lists, etc.).
Example input: [3, 2, 1, 4]
Example output: [1, 2, 3, 4]

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <stack>

using namespace std;

void sortStack(stack<int> &s) {
	stack<int> temp;
	while (!s.empty()) {
		int x = s.top();
		s.pop();
		while (!temp.empty() && temp.top() > x) {
			s.push(temp.top());
			temp.pop();
		}
		temp.push(x);
	}
	while (!temp.empty()) {
		s.push(temp.top());
		temp.pop();
	}
}

int main() {
	stack<int> s;
	s.push(3);
	s.push(2);
	s.push(1);
	s.push(4);
	sortStack(s);
	while (!s.empty()) {
		cout << s.top() << endl;
		s.pop();
	}
	return 0;
}

A.I. Evaluation of the Solution

The candidate's solution correctly sorts the stack in ascending order. The candidate uses an additional stack to hold the elements and correctly pops and pushes the elements in the correct order.

Evaluated at: 2022-11-21 10:16:00