Last active
February 16, 2018 19:03
-
-
Save gcarrillo/e84ebe9d5e72e7c410ff to your computer and use it in GitHub Desktop.
Insertion Sort
This file contains hidden or 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
| #!/usr/bin/env python | |
| ''' | |
| Insertion sort | |
| - Best: O(n) | |
| - Average: O(n^2) | |
| - Worst: O(n^2) | |
| ''' | |
| def insertionsort(l): | |
| for i in xrange(0, len(l)): | |
| val = l[i] | |
| j = i - 1 | |
| # The invariant is that items to the left of l[i] are sorted. | |
| # Because of that, we can move left until we find the first | |
| # item that is smaller than val, and insert after it. | |
| while j >= 0 and l[j] > val: | |
| l[j + 1] = l[j] | |
| j -= 1 | |
| l[j + 1] = val | |
| if __name__ == "__main__": | |
| l = [3, 1, 10, 7, 8, 5, 6, 2] | |
| insertionsort(l) | |
| print l |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment