Created
August 11, 2017 04:19
-
-
Save bytao7mao/0e76e5f05dc39f2ed7d4219792eb74fd to your computer and use it in GitHub Desktop.
Insertion Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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