insertion sort
The Problem
See the sorting problem.
The Algorithm
Suppose is the initial list of unsorted elements. The insertion sort algorithm will construct a new list, containing the elements of in order, which we will call . The algorithm constructs this list one element at a time.
Initially is empty. We then take the first element of and put it in . We then take the second element of and also add it to , placing it before any elements in that should come after it. This is done one element at a time until all elements of are in , in sorted order. Thus, each step consists of looking up the position in where the element should be placed and inserting it there (hence the name of the algorithm). This requires a search, and then the shifting of all the elements in that come after (if is stored in an array). If storage is in an array, then the binary search algorithm can be used to quickly find ’s new position in .
Since at step , the length of list is and the length of list is , we can implement this algorithm as an in-place sorting algorithm. Each step results in becoming fully sorted.
Pseudocode
This algorithm uses a modified binary search algorithm to find the position in where an element should be placed to maintain ordering.
Algorithm Insertion_Sort(L, n)
Input: A list of elements
Output: The list in sorted order
begin
for do
begin
for do
end
end
function Binary_Search(L, bottom, top, key)
begin
if then
else
begin
if then
else
end
end
Analysis
In the worst case, each step requires a shift of elements for the insertion (consider an input list that is sorted in reverse order). Thus the runtime complexity is . Even the optimization of using a binary search does not help us here, because the deciding factor in this case is the insertion. It is possible to use a data type with insertion time, giving runtime, but then the algorithm can no longer be done as an in-place sorting algorithm. Such data structures are also quite complicated.
A similar algorithm to the insertion sort is the selection sort, which requires fewer data movements than the insertion sort, but requires more comparisons.
Title | insertion sort |
Canonical name | InsertionSort |
Date of creation | 2013-03-22 11:44:38 |
Last modified on | 2013-03-22 11:44:38 |
Owner | mathcam (2727) |
Last modified by | mathcam (2727) |
Numerical id | 16 |
Author | mathcam (2727) |
Entry type | Algorithm |
Classification | msc 68P10 |
Classification | msc 55U40 |
Classification | msc 55U99 |
Classification | msc 55U15 |
Classification | msc 55U10 |
Classification | msc 55P20 |
Classification | msc 55-00 |
Classification | msc 85-00 |
Classification | msc 83-02 |
Related topic | SortingProblem |
Related topic | BinarySearch |
Related topic | SelectionSort |