Skip to content

Instantly share code, notes, and snippets.

@ioanzicu
Created July 28, 2022 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ioanzicu/a720668bfbd3277c1ad5eaf11c35a52e to your computer and use it in GitHub Desktop.
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.
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