Created
May 30, 2021 20:51
-
-
Save cgopalan/05f2ea2348b25bd6728973a17e08448d 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
def insertion_sort(nums): | |
nums_length = len(nums) | |
if nums_length < 2: | |
return nums | |
for i in range(1, nums_length): | |
x = i-1 | |
while nums[i] < nums[x] and x >= 0: | |
x -= 1 | |
else: | |
nums.insert(x+1, nums[i]) | |
nums.pop(i+1) | |
return nums | |
if __name__ == '__main__': | |
test_inputs = [ | |
([], []), | |
([3], [3]), | |
([4,5], [4,5]), | |
([7,3], [3,7]), | |
([23,2,3,17,12,18,36,75,74,60], [2,3,12,17,18,23,36,60,74,75]), | |
([1,2,3,4,6,8,10,12,50,54], [1,2,3,4,6,8,10,12,50,54]), | |
([45,23,21,17,11,10,9,6,2], [2,6,9,10,11,17,21,23,45]), | |
] | |
for input, result in test_inputs: | |
print(f"Input: {input}") | |
actual = insertion_sort(input) | |
print(f"Actual: {actual}") | |
assert actual == result, f"expected {result} but was {actual}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment