Skip to content

Instantly share code, notes, and snippets.

@bytao7mao
Created August 11, 2017 04:19
Show Gist options
  • Save bytao7mao/0e76e5f05dc39f2ed7d4219792eb74fd to your computer and use it in GitHub Desktop.
Save bytao7mao/0e76e5f05dc39f2ed7d4219792eb74fd to your computer and use it in GitHub Desktop.
Insertion Sort
Insertion Sort
Suppose A is an array of N values. We want to sort A in ascending order.
Insertion Sort is an algorithm to do this as follows: We traverse the array and insert each element into the sorted part of the list where it belongs. This usually involves pushing down the larger elements in the sorted part.
For I = 1 to N-1
J = I
Do while (J > 0) and (A(J) < A(J - 1)
Temp = A(J)
A(J) = A(J - 1)
A(J - 1) = Temp
J = J - 1
End-Do
End-For
Insertion Sort does roughly N**2 / 2 comparisons and does up to N - 1 swaps.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment