Why is print not printing my array sorted

Tags: , , ,

This is my original array: a = [0, 4, 7, 8, 1, 3, 5, 2, 6]

and this is what it prints: [0, 4, 7, 0, 0, 0, 5, 0, 0]

for i in a:
    pos = i
    min = a[i]
    for j in a:
        if a[j] < min:
            min = a[j]
            pos = j
        a[pos] = a[i]
        a[i] = min


As @’Lee Jun Wei’ it doesn’t look like your algo is right. But there may be a few other things to point out.

These two lines look off.

for i in a:
for j in a:

i and j are taking on the value of the elements of a not the index values. I think you mean

for i in range(len(a)):

The reason you get zeros is because min is initialized to 0. Note that it is zero not because of the index but because 0 is the first value in the array. Once min is zero which is the smallest value in the array this line

if a[j] < min:

Can never be true. So this line

a[i] = min

Sets everything to zero. Every element isn’t zero though because a[i] isn’t sequential. It jumps around because i is the element value not the index.

Source: stackoverflow