Skip to main content
GameDev.net gamedev.net

PRO Tired of ads? Read GameDev.net ad-free and help keep the community independent with GameDev Pro — $3/month.

Article

Insertion Sort

Insertion sort can run in O (n) in the best case, however its worst case is O (n[sup]2[/sup]). It can, however, be used to optimize the quicksort, and is therefore worth learning.

Yin-So Chen
September 13, 1999 5.9k views
The basic step in this algorithm is to insert a data set into a sequence of ordered (increasing) data sets in such way that the resulting sequence of data set is also ordered. Thus if the data set D is inserted in position i, then the data sets in position j less than i will be less than D, and the data sets in position j greater than i will be greater than D.

Since we will be manipulating the data sets in an array, we will have to compare all of the values of the data and move them once the ordering relationship between two values are determined. Below is the pseudo-code of the algorithm.

[font="Verdana, Tahoma, Arial"][size="2"]Insertion Sort (Sorting the array A[size])

For index i = 2 up to i = size
{
While before reach the end of cells
{
Compare the element Awith the preceding element (A[i - 1]).
If the element is smaller than the preceding one (A < A[i - 1]),
swap them;
else, go to the next element.
}
}

[font="Courier New, fixedsys"][size="2"][color="#000088"] [/color][/font][/font]
License: gdol

Related Tutorials

Discussion

Discussion

Loading comments...

More from Yin-So Chen