Lesson 72: Insertion sort
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
Sort like playing cards
- An insertion sort builds a sorted part on the left, one item at a time.
- Take the next item, keep it in
temp, move the items before it to the right while they are smaller, and puttempin the gap. - Bubble sort (lesson 46) swaps neighbours again and again; insertion sort slides each item straight into place.
English
42, 98, 13, 75, 87, 60 (highest first)
| Insert | Array after it |
|---|---|
| 98 | 98 42 13 75 87 60 |
| 13 | 98 42 13 75 87 60 |
| 75 | 98 75 42 13 87 60 |
| 87 | 98 87 75 42 13 60 |
| 60 | 98 87 75 60 42 13 |
English
In the exam
- 9618/31/M/J/21 Q8(a): two factors that affect the performance of a sorting algorithm. Mark scheme: the initial order of the data; the number of data items; the efficiency of the algorithm. Your second program shows the first one: 15 moves or 0 moves for the same 6 numbers.
- 8(b): rewrite a bubble sort as an insertion sort. Mark scheme points include: a FOR loop through the items; temporary storage of the item being inserted; a WHILE loop with the correct exit condition; moving items to the next element; updating the counter; the final insertion.
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Type 6 scores, one per line. Write sortScores as an insertion sort, highest score first. Take each item from index 1 on, keep it in temp, move the smaller items before it one place to the right, and put temp in the gap.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Does the order of the data matter? Count each move (each time an item moves one place right) in moves, print it after the sorted scores, and set it back to 0 for the next 6 scores. Check sends scores in the opposite order (lowest first), then scores that are already in order.
คลิก Run เพื่อดูผลลัพธ์ที่นี่