Math 2.0

Computer science Definition

Insertion sort

Builds on Sorting algorithm

Definition

Let (X,≤)(X, \le) be a totally ordered set. Let x∈Xx \in X and let s=(s1,…,sk)s = (s_1, \dots, s_k) be a sorted sequence over XX. Let jj be the largest index in {0,…,k}\set{0, \dots, k} with j=0j = 0 or sj≤xs_j \le x. The insertion of xx into ss is the sequence (s1,…,sj,x,sj+1,…,sk)(s_1, \dots, s_j, x, s_{j+1}, \dots, s_k). Insertion sort is the sorting algorithm that, on input (a1,…,an)(a_1, \dots, a_n), starts with the empty sequence s(0)s^{(0)}. For i=1,…,ni = 1, \dots, n it lets s(i)s^{(i)} be the insertion of aia_i into s(i−1)s^{(i-1)}, and it returns s(n)s^{(n)}.

Remarks

In the usual array version, jj is found by comparing xx with sk,sk−1,…s_k, s_{k-1}, \dots from the right and shifting each larger element one place. The number of shifts equals the number of inversions of the input, the pairs i<ji < j with ai>aja_i > a_j. So the running time is Θ(n+inv)\Theta(n + \mathrm{inv}), where inv\mathrm{inv} is the number of inversions; it is Θ(n2)\Theta(n^2) on the reversed list, which has n(n−1)/2n(n-1)/2 inversions. Inserting after all equal elements makes the algorithm stable.

Example: on (2,3,1)(2, 3, 1) one gets s(1)=(2)s^{(1)} = (2), s(2)=(2,3)s^{(2)} = (2, 3) since 2≤32 \le 3, and s(3)=(1,2,3)s^{(3)} = (1, 2, 3), since j=0j = 0 for x=1x = 1.

Non-example: appending each aia_i at the end of s(i−1)s^{(i-1)} instead of at position j+1j + 1 just copies the input, and (2,1)(2, 1) stays unsorted.

Reading path

To understand this page from the ground up, read these 2 pages in order. The foundations come first.

Show the path as a graph
Each page uses the pages above it. The colour of the bar on a box shows how strong the evidence is, and the box also gives it as text. The list has the same pages.
  • no evidence level
  1. Sorting algorithm concept
  2. Insertion sort definition

Further reading

  1. Web https://en.wikipedia.org/wiki/Insertion_sort
About this page
Tag5DYWS7DVQJ
URIm2://5DYWS7DVQJ
Kinddefinition
WritingW0 stub
MSC68P10, 68W40
DefinesInsertion sort
UsesSorting algorithm
Changed3 November 2026

Markdown · JSON · Edit on GitHub

What this page needs for W1

  • an inventory row: the row of the inventory that the node accounts for (0 of 1)
  • a source with a locator (0 of 1)

The writing levels say how complete the text of a page is. They do not measure its truth.

What links here

No page links to this page yet.