insertion sort algo

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nikhil124
    New Member
    • Jan 2010
    • 6

    insertion sort algo

    consider this insertion sort algo(from cormen)
    INSERTION-SORT(A)
    Code:
        for j<--- 2 to length[A]
            do key<--- A[j]
            >Insert A[j] into the sorted seq A[1......j-1].
            i <---  j -1
            while i > 0 and A[i] > key 
                do A[i+1]<--- A[i]
                i <--- i - 1
            A[i+ 1] <--- key
    i'm unable to understand from line 6 to 8.
    in 6) we put value of A[i] in A[i+1] , then again we put value of "key " in A[i+1] in line 8).How's that possible.what is the meaning of line 7) i'm unable to interpret it.
    plz help, where i'm making mistake
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The whole thing makes more sence with the white space preserved so the structure is clear. I have edited your post to do this. Also not this sudo code starts arry/list indexes at 1.

    Lines 6 and 7 are responsible for moving the correct part of the currently sorted list down 1 item at a time until a space is made for the item currently being sorted at the correct location to maintain the sorting.

    Line 8 then puts the item currently being sorted into that space.

    For example imagine we are sorting the list

    1, 3, 5, 7, 4, <OtherData>

    and j is 5

    key = A[j] = 4

    After running the loop in lines 4 - 7 the list looks like this

    1, 3, 5, 5, 7, <OtherData>

    and i has a value of 2

    Line 8 reinserts the key at i+1

    A[i+1] = key = 4

    And the list finishes that iteration as

    1, 3, 4, 5, 7, <OtherData>

    ready to sort the <OtherData>

    Comment

    Working...