2.1Insertion sort17123456524613(a)254613(b)245613(c)245613(d)13(e)245613(f)Figure 2.2The operation of INSERTION-SORT on the arrayA=±5,2,4,6,1,3². Array indicesappear above the rectangles, and values stored in the array positions appear within the rectangles.(a)–(e)The iterations of theforloop of lines 1–8. In each iteration, the black rectangle holds thekey taken fromA[j], which is compared with the values in shaded rectangles to its left in the test ofline 5. Shaded arrows show array values moved one position to the right in line 6, and black arrowsindicatewherethekeyismovedtoinline8.(f)The ﬁnal sorted array.INSERTION-SORT(A)1forj←2tolength[A]2dokey←A[j]3✄InsertA[j] into the sorted sequenceA[1..j−1].4i←j−15whilei>0andA[i]>6doA[i+1]←A[i]7i←i−18A[i+1]←Loop invariants and the correctness of insertion sortFigure 2.2 shows how this algorithm works forA5,2,4,6,1,3².Thein-dexjindicates the “current card” being inserted into the hand. At the beginning
This is the end of the preview.
access the rest of the document.