40_split_Introduction to Algorithms 2nd Edition

40_split_Introduction to Algorithms 2nd Edition - 2.1...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
2.1 Insertion sort 17 123456 5 2 4613 (a) 25 4 613 (b) 245 6 13 (c) 2456 1 3 (d) 1 3 (e) 2 4 5 6 1 3 (f) Figure 2.2 The operation of INSERTION-SORT on the array A 5 , 2 , 4 , 6 , 1 , 3 ² . Array indices appear above the rectangles, and values stored in the array positions appear within the rectangles. (a)–(e) The iterations of the for loop of lines 1–8. In each iteration, the black rectangle holds the key taken from A [ j ], which is compared with the values in shaded rectangles to its left in the test of line 5. Shaded arrows show array values moved one position to the right in line 6, and black arrows indicatewherethekeyismovedtoinline8 . (f) The final sorted array. INSERTION-SORT ( A ) 1 for j 2 to length [ A ] 2 do key A [ j ] 3 Insert A [ j ] into the sorted sequence A [1 .. j 1]. 4 i j 1 5 while i > 0and A [ i ] > 6 do A [ i + 1] A [ i ] 7 i i 1 8 A [ i + 1] Loop invariants and the correctness of insertion sort Figure 2.2 shows how this algorithm works for A 5 , 2 , 4 , 6 , 1 , 3 ² .T h ei n - dex j indicates the “current card” being inserted into the hand. At the beginning
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.
Ask a homework question - tutors are online