Here is how to Sort using Selection Sort in Python. One function keeps moving maximum value at the end, the other moves minimum value at the beginning.
Run the code here: https://repl.it/@VinitKhandelwal/selection-sort
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run the code here: https://repl.it/@VinitKhandelwal/selection-sort
def selectionSortMax(list1):
a = len(list1)
for i in range(0,a):
high = list1[0]
high_index = 0
for j in range(0,a):
if list1[j] > high:
high = list1[j]
high_index = j
a -= 1
temp = list1[a]
list1[a] = list1[high_index]
list1[high_index] = temp
return list1
def selectionSortMin(list1):
a = len(list1)
for i in range(0, a):
minimum = i
temp = list1[i]
for j in range(i+1, a):
if list1[j] < list1[minimum]:
minimum = j
list1[i] = list1[minimum]
list1[minimum] = temp
return list1
print(selectionSortMax([5,3,7,6,1,9,0,2,4,8]))
print(selectionSortMin([5,3,7,6,1,9,0,2,4,8]))
OUTPUT
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Comments
Post a Comment