Regarding Selection Sort Algorithm. Let's assume that my array has 10 elements. If I leave len() and remove the -1 in the loop that belongs to the selection_sort() function I get that in the last iteration that i will be equal to 9. So we pass that value to the select() function and it is gonna start with j=10, and there is no such a thing. The program should rise an error since there is no such thing as if array[9] > array[10], array[10] does not exist, instead, the program shows the array sorted. Why doesn't the program rise an error?
def select(array, start):
minIndex = start
for j in range(start + 1, len(array)):
if array[minIndex] > array[j]:
minIndex = j
def selection_sort(array):
# If I put len(array) removing the -1, I get it sort it anyway
for i in range(len(array) - 1 ): # Here, I do not get it
minIndex = select(array, i)
tmp = array[i]
array[i] = array[minIndex]
array[minIndex] = tmp
Output:
Unsorted array: [9, 7, 3, 10, 2, 6, 4, 5, 8, 1]
Iteration i = 0
Iteration j = 1
Iteration j = 2
Iteration j = 3
Iteration j = 4
Iteration j = 5
Iteration j = 6
Iteration j = 7
Iteration j = 8
Iteration j = 9
[1, 7, 3, 10, 2, 6, 4, 5, 8, 9]
Iteration i = 1
Iteration j = 2
Iteration j = 3
Iteration j = 4
Iteration j = 5
Iteration j = 6
Iteration j = 7
Iteration j = 8
Iteration j = 9
[1, 2, 3, 10, 7, 6, 4, 5, 8, 9]
Iteration i = 2
Iteration j = 3
Iteration j = 4
Iteration j = 5
Iteration j = 6
Iteration j = 7
Iteration j = 8
Iteration j = 9
[1, 2, 3, 10, 7, 6, 4, 5, 8, 9]
Iteration i = 3
Iteration j = 4
Iteration j = 5
Iteration j = 6
Iteration j = 7
Iteration j = 8
Iteration j = 9
[1, 2, 3, 4, 7, 6, 10, 5, 8, 9]
Iteration i = 4
Iteration j = 5
Iteration j = 6
Iteration j = 7
Iteration j = 8
Iteration j = 9
[1, 2, 3, 4, 5, 6, 10, 7, 8, 9]
Iteration i = 5
Iteration j = 6
Iteration j = 7
Iteration j = 8
Iteration j = 9
[1, 2, 3, 4, 5, 6, 10, 7, 8, 9]
Iteration i = 6
Iteration j = 7
Iteration j = 8
Iteration j = 9
[1, 2, 3, 4, 5, 6, 7, 10, 8, 9]
Iteration i = 7
Iteration j = 8
Iteration j = 9
[1, 2, 3, 4, 5, 6, 7, 8, 10, 9]
Iteration i = 8
Iteration j = 9
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iteration i = 9
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
-1from theforloop that belongs to the second function. So in that case we would havefor i in range(len(array)), thus if the array has 10 elements it goes from 0 to 9