Last active
March 6, 2019 18:09
-
-
Save gozeloglu/e29377a45e7fa842bd9cb3c56304f5dc to your computer and use it in GitHub Desktop.
This is an selection sort algorithm implemented in Python
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
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