from finding the minimun and put it on the left to finding the maximum and put it on the right
def SelectionSort(a_list):
n = len(a_list)
for i in range(0, n-1):
iMin = i
print(a_list)
for j in range(i+1, n):
if a_list[j] < a_list[iMin]:
iMin = j
temp = a_list[i]
a_list[i] = a_list[iMin]
a_list[iMin] = temp
print()
return a_list
someList = [45,984,6,90,8946,89]
SelectionSort(someList)
Can it swap the process from minimum => maximum to minimum <= maximum
the answer should look like this.
[6, 45, 89, 89, 984, 8946]
>Solution :
Yes:
- Rename
iMintoiMax - Mirror the two ranges you use:
range(0, n-1)becomesrange(n-1, 0, -1)range(i+1, n)becomesrange(i-1, -1, -1)
- Mirror the comparison operator
<becomes>
Result:
def SelectionSort(a_list):
n = len(a_list)
for i in range(n-1, 0, -1):
iMax = i
print(a_list)
for j in range(i-1, -1, -1):
if a_list[j] > a_list[iMax]:
iMax = j
temp = a_list[i]
a_list[i] = a_list[iMax]
a_list[iMax] = temp
print()
return a_list
Unrelated to your question (and as commented), swapping can be done like this:
a_list[i], a_list[iMax] = a_list[iMax], a_list[i]