samedi 2 avril 2016

python swap sort not giving correct output

I'm trying to sort an array where it starts from the second number and looks at the one before it to see if the previous number is larger. If it is, I want to swap the numbers, otherwise keep the number where it is. Currently my code does not do that. When I input the array below the only thing that changes is that the 2 becomes an 11, giving me two 11's in the middle. What is going wrong?

#given an array of digits a of length N
a = [7, 3, 11, 2, 6, 16]
N = len(a)

# moving forward along a starting from the second position to the end

# define _sillysort(a, start_pos):
#     set position = start_pos
#     moving backwards along a from start_pos:
#         if the a[position-1] is greater than a[position]:
#             swap a[position-1] and a[position]
def sillysort(a, start_pos):
    a_sorted = []
    start_pos = a[1]
    for position in a:
        if a[start_pos-1] >= a[start_pos]:
            a[start_pos-1], a[start_pos] = a[start_pos], a[start_pos-1]
        else:
            a[start_pos-1] = a[start_pos]
        a_sorted.append(position)
        position += 1
    return a_sorted

When I run this, sillysort(a, N), I get this output [7, 3, 11, 11, 6, 16].

Aucun commentaire:

Enregistrer un commentaire