Created
June 13, 2021 14:42
-
-
Save cgopalan/5becd29a794d0380e33b0c78d6a02bfd to your computer and use it in GitHub Desktop.
selectionsort.py
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 selection_sort(nums): | |
nums_length = len(nums) | |
if nums_length < 2: | |
return nums | |
for k in range(nums_length): | |
for i in range(k, nums_length): | |
if i == k: | |
smallest_idx, smallest = i, nums[i] | |
else: | |
if smallest > nums[i]: | |
smallest_idx, smallest = i, nums[i] | |
# Swap between lists | |
nums.insert(k, smallest) | |
nums.pop(smallest_idx + 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 = selection_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