Sorting Algorithms in Python
- sam33frodon
- Feb 16, 2021
- 1 min read
1. Selection sort
Method 1
def selectionSort(array):
n = len(array)
for i in range(n):
# Initially, assume the first element of the unsorted part as the minimum.
minimum = i
for j in range(i+1, n):
if (array[j] < array[minimum]):
# Update position of minimum element if a smaller element is found.
minimum = j
# Swap the minimum element with the first element of the unsorted part.
temp = array[i]
array[i] = array[minimum]
array[minimum] = temp
return array
array = [13, 4, 9, 5, 3, 16, 12]
print(selectionSort(array))
[3, 4, 5, 9, 12, 13, 16]
Method 2
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
[17, 20, 26, 31, 44, 54, 55, 77, 93]
(To be continued)
Comments