Skip to content

Instantly share code, notes, and snippets.

@anchitarnav
Created November 14, 2021 10:48
Show Gist options
  • Select an option

  • Save anchitarnav/fd7fd3fd723b506a4c3d04dcb9578144 to your computer and use it in GitHub Desktop.

Select an option

Save anchitarnav/fd7fd3fd723b506a4c3d04dcb9578144 to your computer and use it in GitHub Desktop.
Selection Sort Python implementation
# Selection Sort --> Python Implementation
# The smallest element from the UNSORTED array shall always be on the right of the SORTED array
# This is similar to heap sort where the smallest element comes out everytime.
def selection_sort(array: list):
for smallest_unsorted in range(0, len(array)):
smallest_index = smallest_unsorted
smallest_element = array[smallest_index]
for i in range(smallest_index, len(array)):
if array[i] < smallest_element:
smallest_element = array[i]
smallest_index = i
# swap
array[smallest_unsorted], array[smallest_index] = array[smallest_index], array[smallest_unsorted]
if __name__ == '__main__':
import random, copy
arr = [num for num in range(10)]
random.shuffle(arr)
print(f"Unsorted => {arr}")
selection_sort(arr)
print(f"Sorted => {arr}")
assert arr == sorted(copy.deepcopy(arr)), "Not Sorted properly"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment