Use the original stack to hold items in two sections: sorted (bottom) and unsorted (top).
Utilize a temporary stack to help in repositioning items.
Process each item by selecting the top of the original stack, moving unsorted items to the temporary stack, placing the item in its proper position in the sorted section, and then moving items back from the temporary stack to the original stack.
To summarize:
Start with all items in the unsorted section of the original stack.
For each item, remove it from the stack, find its proper position in the sorted section, and place it there.
Use the temporary stack to manage intermediate steps.
publicclassSolution {
publicstaticvoidinsertionSortStack(Stack<Integer> items) {
Stack<Integer> tempStack =new Stack<>();
int numItems = items.size();
for (int i = 0; i < numItems; i++) {
// Take the next item to be sortedint nextItem = items.pop();
// Move all unsorted items to the temporary stackfor (int j = 0; j < numItems - i - 1; j++) {
tempStack.push(items.pop());
}
// Move sorted items until finding the correct position for nextItemwhile (!items.isEmpty() && items.peek() > nextItem) {
tempStack.push(items.pop());
}
// Insert the next item in its correct place in sorted section items.push(nextItem);
// Move items back from tempStack to the original stackwhile (!tempStack.isEmpty()) {
items.push(tempStack.pop());
}
}
}
publicstaticvoidmain(String[] args) {
Stack<Integer> stack =new Stack<>();
stack.push(4);
stack.push(2);
stack.push(3);
stack.push(1);
System.out.println("Original stack: "+ stack);
insertionSortStack(stack);
System.out.println("Sorted stack: "+ stack);
}
}
classSolution:
definsertionSortStack(self, stack: List[int]) -> List[int]:
temp_stack: List[int] = []
num_items = len(stack)
for i in range(num_items):
# Take the next item to be sorted next_item = stack.pop()
# Move all unsorted items to the temporary stackfor _ in range(num_items - i -1):
temp_stack.append(stack.pop())
# Move sorted items until finding the correct position for next_itemwhile stack and stack[-1] > next_item:
temp_stack.append(stack.pop())
# Insert the next item in its correct place in sorted section stack.append(next_item)
# Move items back from temp_stack to the original stackwhile temp_stack:
stack.append(temp_stack.pop())
return stack
# Test the implementationsol = Solution()
stack = [4, 2, 3, 1]
print("Original stack:", stack)
sorted_stack = sol.insertionSortStack(stack)
print("Sorted stack:", sorted_stack)