Johnathan
Johnathan

Reputation: 449

Proper Python SelectionSort

I am trying to learn the selection sort using python, but can't get my code to work. Some assistance would be appreciated.

def selection(seq):
    for x in range(len(seq)):
    temp = 0
        for y in range(1, len(seq)):
            if seq[y] < seq[temp]:
            temp = y
    if temp != 0:    
        seq[x], seq[temp] = seq[temp], seq[x]
    return seq

selection([12, 38, 2, 18, 15, 1, 19])

Upvotes: 0

Views: 41

Answers (1)

aldarel
aldarel

Reputation: 456

You mixed indexes for both loops and initialisation of temp. You can fix it with this code:

def selection(seq):
    for x in range(len(seq)):
        temp = x
        for y in range(x+1, len(seq)):
            if seq[y] < seq[temp]:
                temp = y
        seq[x], seq[temp] = seq[temp], seq[x]
    return seq

seq = [5, 3, 1, 2, 4]
print(selection(seq))

Upvotes: 2

Related Questions