เราจำเป็นต้องเขียนฟังก์ชัน 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 ]