Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เรียงลำดับองค์ประกอบของสแท็กด้วย JavaScript


เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของจำนวนเต็ม โดยใช้ recursion และเมธอด push และ pop ของอาร์เรย์ ฟังก์ชันควรเรียงอาร์เรย์แบบ in-place

ตัวอย่างโค้ด

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

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 ]