chelseawangsf
5/6/2018 - 6:03 AM

[Sort with 2 stacks]#来offer#Selection Sort #Stack

[Sort with 2 stacks]#来offer#Selection Sort #Stack

/** Given an array that is initially stored in one stack, sort it with one additional stacks (total 2 stacks).

After sorting the original stack should contain the sorted integers and from top to bottom the integers are sorted in ascending order.

Assumptions:

The given stack is not null.
Requirements:

No additional memory, time complexity = O(n ^ 2).
*/

public class Solution {
  public void sort(LinkedList<Integer> s1) {
    if (s1 == null || s1.size() == 0 || s1.size() == 1) {
    	return;
    }
    LinkedList<Integer> helper = new LinkedList<Integer>();
    // Write your solution here.
    while (!s1.isEmpty()) {
    	int cur = s1.pop();
      while (!helper.isEmpty() && cur < helper.peek()) {
      	s1.push(helper.pop());
      }
      helper.push(cur);
    }
    
    while (!helper.isEmpty()) {
    	s1.push(helper.pop());
    }
  }
}