使用 JavaScript 对堆栈元素进行排序
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/8 5:00:17
我们需要编写一个 JavaScript 函数,该函数接受一个整数数组。利用递归和数组的推送和弹出方法,该函数应该对数组进行就地排序。
示例
其代码为 −
const stack = [−3, 14, 18, −5, 30];
const sortStack = (stack = []) => {
if (stack.length > 0) {
let t = stack.pop();
sortStack(stack);
sortedInsert(stack, t);
};
}
const sortedInsert = (stack, e) => {
if (stack.length == 0 || e > stack[stack.length − 1]) {
stack.push(e);
} else {
let x = stack.pop();
sortedInsert(stack, e);
stack.push(x);
}
}
sortStack(stack);
console.log(stack);
输出
控制台中的输出将是 −
[ −5, −3, 14, 18, 30 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

