使用 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 ]
廣告
資料結構
網路連線
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP