Created
July 28, 2022 05:24
-
-
Save ioanzicu/a720668bfbd3277c1ad5eaf11c35a52e to your computer and use it in GitHub Desktop.
Implementation of Selection Sort in Python 3 with increasing or decreasing order of the items.
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 find_min(nums): | |
lowest = nums[0] | |
lowest_index = 0 | |
for i in range(len(nums)): | |
if lowest > nums[i]: | |
lowest = nums[i] | |
lowest_index = i | |
return lowest_index | |
def find_max(nums): | |
highest = nums[0] | |
highest_index = 0 | |
for i in range(len(nums)): | |
if highest < nums[i]: | |
highest = nums[i] | |
highest_index = i | |
return highest_index | |
def selection_sort(nums, reverse=False): | |
output = [] | |
item = 0 | |
for _ in range(len(nums)): | |
if reverse: # Ex: [3, 2, 1] | |
item = find_max(nums) | |
else: # Ex: [1, 2, 3] | |
item = find_min(nums) | |
output.append(nums.pop(item)) | |
return output | |
nums = [1, 333, 555, 5, 33, 44, 88, 999, 9, 0, 22, 666] | |
result = selection_sort(nums) | |
print(result) | |
nums = [1, 333, 555, 5, 33, 44, 88, 999, 9, 0, 22, 666] | |
result = selection_sort(nums, reverse=True) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment