Created
October 12, 2019 17:12
-
-
Save njacobs5074/4af3f87f8273cd3a0a43ab4cfd9b06f0 to your computer and use it in GitHub Desktop.
Simple Insertion Sort in Python
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 random | |
| import sorting | |
| # Color Code -- 2019-10-12 | |
| # Create 20 random number from -10 to +10 | |
| my_randoms = random.sample(xrange(-10, 11), 20) | |
| print("20 random numbers:") | |
| print(my_randoms) | |
| # Sort the random numbers above and print them out. | |
| print("Sorted:") | |
| print(sorting.insert_sort(my_randoms)) | |
| print(sorting.insert_sort([-2, -4, 3, 2, 1])) | |
| print("\nSorted numbers w/duplicates") | |
| print(sorting.insert_sort([0, 1, 2, 3, 3])) | |
| print(sorting.insert_sort([1, 2])) |
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
| def insert_sort(array_of_numbers): | |
| i = 1 | |
| while i < len(array_of_numbers): | |
| j = i | |
| while j > 0 and array_of_numbers[j - 1] > array_of_numbers[j]: | |
| tmp = array_of_numbers[j - 1] | |
| array_of_numbers[j - 1] = array_of_numbers[j] | |
| array_of_numbers[j] = tmp | |
| j = j - 1 | |
| i = i + 1 | |
| return array_of_numbers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment