Selection sort

Selection sort works by selecting the smallest number in the "unsorted" part of the array, and then swapping it with the rightmost position of the "sorted" part of the array. So there's 3 counters that's needed for this, 'i', which goes through the unsorted array to find the smallest number, 'smallest_index', which records the index of the smallest number in the unsorted array, and 'marker' which marks the beginning of the unsorted array and where the smallest number of the unsorted list needs to go. It stops and exits when the marker reaches the end of the array.
def selection(numblimit, amountlimit):
numberlist = []
i = 0
while i < amountlimit:
numberlist.append(random.randint(1, numblimit))
i += 1
print("initial: ", numberlist)
i = 0
marker = 0
while marker < len(numberlist):
smallest_index = marker
while i < len(numberlist):
if numberlist[i] < numberlist[smallest_index]:
smallest_index = i
i += 1
temp = numberlist[marker]
numberlist[marker] = numberlist[smallest_index]
numberlist[smallest_index] = temp
marker += 1
return numberlist
Comments
Post a Comment