js用栈实现排序
使用栈实现排序的方法
在JavaScript中,可以通过两个栈来模拟排序算法。这种方法类似于插入排序,利用辅助栈来保持元素的顺序。以下是具体实现步骤:
初始化两个栈
创建一个主栈stack用于存放未排序的元素,另一个辅助栈tempStack用于临时存放已排序的元素。
const stack = [34, 3, 31, 98, 92, 23];
const tempStack = [];
排序过程
从主栈中弹出元素,与辅助栈的栈顶元素比较,确保辅助栈中的元素始终按升序排列。
while (stack.length > 0) {
const current = stack.pop();
while (tempStack.length > 0 && tempStack[tempStack.length - 1] > current) {
stack.push(tempStack.pop());
}
tempStack.push(current);
}
结果输出
排序完成后,辅助栈tempStack中的元素即为升序排列的结果。
console.log(tempStack); // [3, 23, 31, 34, 92, 98]
完整代码示例
以下是将上述步骤整合为一个完整函数的代码:
function sortStack(stack) {
const tempStack = [];
while (stack.length > 0) {
const current = stack.pop();
while (tempStack.length > 0 && tempStack[tempStack.length - 1] > current) {
stack.push(tempStack.pop());
}
tempStack.push(current);
}
return tempStack;
}
const stack = [34, 3, 31, 98, 92, 23];
const sortedStack = sortStack(stack);
console.log(sortedStack); // [3, 23, 31, 34, 92, 98]
注意事项
- 该方法的时间复杂度为O(n²),适合小规模数据排序。
- 确保主栈中的元素全部弹出并正确插入辅助栈,否则会导致排序失败。







