Created
July 3, 2014 04:58
-
-
Save lapointexavier/0cfde71c0199e330f498 to your computer and use it in GitHub Desktop.
Simple insertion sort algo
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
| import operator as op | |
| def insertion_sort(data, reverse=False): | |
| order = op.gt | |
| if reverse: | |
| order = op.lt | |
| for j in range(len(data)): | |
| key = data[j] | |
| i = j - 1 | |
| while i >= 0 and order(data[i], key): | |
| data[i + 1] = data[i] | |
| i = i - 1 | |
| data[i + 1] = key | |
| print('Sorted data (reverse={0}): {1}'.format(reverse, data)) | |
| if __name__ == '__main__': | |
| sample = [31, 41, 59, 26, 41, 58] | |
| insertion_sort(sample) | |
| insertion_sort(sample, reverse=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment