0

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
print(a)
1
  • 1
    You are confusing list values with list indexes, which is only possible because all of the values happen to be valid indexes for the list. If you made sure that wasn't true (by adding 10 to each value in your list, for example), then any such confusion will cause an exception right at the point of the problem, rather than allowing meaningless results to persist until the end of the code. Commented Aug 14, 2020 at 2:57

3 Answers 3

4

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.

2

Hmm, what sorting algorithm are you trying to implement? If what you're trying to do is a bubble sort, it should be like so:

a = [0, 4, 7, 8, 1, 3, 5, 2, 6]

n=len(a)

for i in range(n):
    for j in range(n-1):
        if a[j+1] < a[j]:
            min = a[j+1]
            a[j+1] = a[j]
            a[j] = min

print(a)
1
  • I was going for a selection sort, but I was missing the n = leng part
    – Argie
    Commented Aug 14, 2020 at 2:20
0

You didn't explain what exactly you want but if you want to sort your array from, for example, 45312 to 12345 ...

print(sorted(mylist))
a=sorted(mylist)# store in a variable 

Not the answer you're looking for? Browse other questions tagged or ask your own question.