def selection_sort(numbers) -> []:
if len(numbers) < 2:
return numbers
m = min(numbers)
for i in range(len(numbers)):
if numbers[i] == m:
t = numbers[0]
numbers[0] = numbers[i]
numbers[i] = t
numbers[1:len(numbers)] = selection_sort(numbers[1: len(numbers)])
return numbers
if __name__ == "__main__":
nums = [33, 1, 89, 2, 67, 245]
print(f"sorted = {selection_sort(nums)}\n")
It outputs:
// running tests
6. Your selection_sort function should follow the selection sort algorithm, swapping the minimum value in the unsorted part of the list with the first unsorted element. Avoid unnecessary swaps when the minimum value is already in the correct position.
// tests completed
// console output
sorted = [1, 2, 33, 67, 89, 245]
I changed the code to address the two cases above.
def selection_sort(numbers) -> []:
if len(numbers) < 2:
return numbers
m = min(numbers)
for i in range(len(numbers)):
if numbers[i] == m:
if i != 0: # only do the swap if it is not already in its place
t = numbers[0]
numbers[0] = numbers[i]
numbers[i] = t
break # once you did a swap do not do it for any others
numbers[1:len(numbers)] = selection_sort(numbers[1: len(numbers)])
return numbers
if __name__ == "__main__":
nums = [33, 2, 11, 2, 2, 67, 245]
print(f"sorted = {selection_sort(nums)}\n")
Still the same error is shown. No clue yet why.
Is there a way I can see my code’s problem by myself as @ILM mentioned the two points regarding it?
def selection_sort(numbers) -> []:
if len(numbers) < 2:
return numbers
m = min(numbers)
for i in range(len(numbers)):
if numbers[i] == m:
if numbers[i] != numbers[0]: # only do the swap if it is not already in its place
t = numbers[0]
numbers[0] = numbers[i]
numbers[i] = t
break # once you did a swap do not do it for any others
numbers[1:len(numbers)] = selection_sort(numbers[1: len(numbers)])
return numbers
if __name__ == "__main__":
nums = [33, 1, 89, 2, 67, 245]
nums = [1, 1, 2]
nums = [1, 1, 5, 1, 2]
print(f"sorted = {selection_sort(nums)}\n")
While it’s true your current approach provides the correct sorted array, you are not using the standard selection sort algorithm to do it, so the test doesn’t pass.
Try using an approach that doesn’t rely on recursion.