使用 JavaScript 排序棧的元素


我們需要編寫一個 JavaScript 函式,該函式接收一個整數陣列。使用陣列的遞迴和 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 ]

更新於:2020 年 11 月 23 日

239 次瀏覽

職業生涯起航

完成此課程並透過認證

開始
廣告
© . All rights reserved.