Skip to content

Instantly share code, notes, and snippets.

@gozeloglu
Last active March 6, 2019 18:09
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 gozeloglu/e29377a45e7fa842bd9cb3c56304f5dc to your computer and use it in GitHub Desktop.
Save gozeloglu/e29377a45e7fa842bd9cb3c56304f5dc to your computer and use it in GitHub Desktop.
This is an selection sort algorithm implemented in Python
import random as rd
''' Complexity : O(n^2)
It looks at each elements and makes comparision
like (n-1), (n-2), ..., 1
So, if we sum up all comparisions, the result will be (n * (n-1)) / 2
Because of the summation, the complexity will be O(n^2)'''
def selectionSort(arr):
min_ind = 0 # min_value's index
for i in range(len(arr)): # Traverse the all list
min_ind = i
for j in range(i, len(arr)):
if arr[j] < arr[min_ind]: # Compares the minimum value and each value in array
min_ind = j # Finds the minimum value
""" Swap """
tmp = arr[i]
arr[i] = arr[min_ind]
arr[min_ind] = tmp
print(arr)
# Tests
for _ in range(5):
arr = [rd.randint(0,20) for i in range(10)]
selectionSort(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment