使用JavaScript对堆栈元素进行排序
我们需要编写一个JavaScript函数,该函数接受一个Integer数组。利用递归和数组的push和pop方法,该函数应就位对数组进行排序。
示例
为此的代码将是-
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 ]
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短