I have implemented the selection sort in python, but couldn't understand this tiny part of inner for loop.
The for
loop for j
, I have the range from outer index i
to max length-1, this makes a lot of sense to me, but the result wouldn't count the last number in the array, and I can't think of the reason.
However, If I change the range from i
to max length, it would work. (which in my knowledge should be exceeding the array since alist[len(alist)]
would count 1 digit pass the max number).
#Go over the loop, find the smallest num
def swap(arr, num_1, num_2):
temp = arr[num_1]
arr[num_1] = arr[num_2]
arr[num_2] = temp
def selectionSort(alist):
for i in range(0, len(alist)-1):
min = i
# for j in range(i+1, len(alist)):
# Why len(alist)-1 doesn't work?
for j in range(i, len(alist)-1):
if alist[j] < alist[min]:
min = j
if min != i :
swap(alist,i,min)
return alist
# Test
print "-------------Test--- ----------"
A = [2,1,9,3,4,100,99,30]
print selectionSort(A)
Read about ranges in Python again; you don't have a clear concept of
them. range(0, 3)
, for example, is roughly equivalent to [0, 1, 2]
.
It stops just short of the second value. The same is true of slices.