-1

This may seem like a simple question but when I attempted to implement selection sort in Python, I do not get a sorted list. Is there something wrong with my implementation?

def selectionSort (B, annotate=True):
    for i in range(len(A)):
    for j in range(1,len(A)):
        if(A[i] > A [j]):
            A[i], A[j] = A[j], A[i]



A = [5, 4, 3, 2, 1]
A_sorted = selectionSort (A)
print ("Sorted " + str(A) + " = " + str(A_sorted))

A = [10, 7, 8, 40, 2, 5]
A_sorted = selectionSort (A)
print ("Sorted " + str(A) + " = " + str(A_sorted))

Here's what I get:

>>> (executing lines 1 to 74 of "selection_sort_103_v2.py")

Sorted [1, 5, 4, 3, 2] = None

Sorted [2, 40, 10, 8, 7, 5] = None
4
  • 1
    you don't return anything from your function. Besides you don't use parameter B: all the work is done on global A Commented Oct 10, 2016 at 20:39
  • please fix your indentation Commented Oct 10, 2016 at 20:39
  • Does it do this? - youtube.com/watch?v=Ns4TPTC8whw Commented Oct 10, 2016 at 20:41
  • @wwii: if only, but no. Commented Oct 10, 2016 at 20:42

1 Answer 1

0

Could try this. Your index for j is fixed from 1 too which needs to vary according to i.

def selectionSort (A, annotate=True):
    for i in range(len(A)):
      for j in range(i+1,len(A)):
          if(A[i] > A [j]):
              A[i], A[j] = A[j], A[i]

    return A    

Checking for values:

A = [5, 4, 3, 2, 1]
print selectionSort(A)
>>[1, 2, 3, 4, 5]

Also, if you want to print both the old and new arrays might want to save the old array by referencing it.

A = [5, 4, 3, 2, 1]
Arr=A[:]
A_sorted=selectionSort(A)
print ("Sorted " + str(Arr) + " = " + str(A_sorted))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.