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.