Sorting algorithms/Insertion sort

From Rosetta Code
Revision as of 22:18, 11 November 2007 by rosettacode>Mwn3d (Created page from Help:Request a new programming task.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Sorting algorithms/Insertion sort
You are encouraged to solve this task according to the task description, using any language you may know.

An O(n^2) sorting algorithm which moves elements one at a time into the correct position. The algorithm is as follows (from the wikipedia):

insertionSort(array A)
        for i = 1 to length[A]-1 do
               value = A[i] 
               j = i-1
               while j >= 0 and A[j] > value do 
                        A[j + 1] = A[j]
                        j = j-1
               A[j+1] = value