CC-Q3.5 sort stack

we could use selection sort which needs two more stack
we could use insertion sort which needs one more stack.

//implement insertion sort 
public class Solution {
    public void sort(Stack<Integer> s) {
        Stack<Integer> s2 = new Stack<Integer>();
        while (!s.isEmpty()) {
            // Insert each element in s in sorted order into s2(nondescending order)
            int tmp = s.pop();
            while (!s2.isEmpty() && s2.peek() > tmp) {
                s.push(s2.pop());
            }
            s2.push(tmp);
        }
        
        //Copy the elements from s2 back into s.
        while (!s2.isEmpty()) {
            s.push(s2.pop());
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容