I understand the concept of Selection Sort (I think) but what I'm confused about is trying to code it. From my understanding of Selection Sort, you set the first element as your minimum value and then compare it with the second element, and if the second element is smaller, you swap the elements together, making the second element your minimum value, and the previous min value goes to the position of where the second element was but if not, you continue looping through the list. You keep doing this until the list has been sorted.
def selection_sort(arr):
for x in range(len(arr)):
minimum_index = 0
for y in range(x+1, len(arr)):
print(arr[minimum_index], arr[y])
if arr[y] < arr[minimum_index]:
minimum_index = y
arr[x], arr[minimum_index] = arr[minimum_index], arr[x]
return arr
I copied a code online, and changed it a bit to try and understand it. My question is, why can't minimum_index be equal to 0 if you're trying to compare it to other elements, and then swapping it. And also, why is arr[x], arr[minimum_index] = arr[minimum_index], arr[x] within the outer for loop body and not inside the inner for loop.
Is it also possible to try and explain in terms a beginner would understand and also maybe some example.
Sorry if any of the questions sound stupid. I'm still trying to understand Data Structures and Algorithms.
minimum_indexis set to 0 right before the second loop. So, before updating it, you are indeed doing the comparison againstarr[0].x, chosen in the outer loop, once you got the indexythat you want to swap, you do the swapping. The purpose of the inner loop is to get the indexyfor minimumarr[y]. If you were to make the swap before finishing the inner loop, you could do many swaps before getting the righty.[35, 68, 16, 84, 2, 46]. Did you tried the original code before changing it? Maybe it's because of your changes?xvalues guards these against further swaps, ie it keeps a barrier between those that are sorted and those yet to be sorted.