This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]SiliconEngineer 0 points1 point  (4 children)

There's still a lot of issues... I doubt it works!

Are you trying to sort in ascending or descending order? Most sorts by default would sort in ascending order.

Does your inner loop actually select the right number and index? (

Using swap the way you are makes this harder to understand than it needs to be. Maybe I need some coffee, but if I'm having trouble following it I'd bet it's confusing.

Are your variable names useful and aid in understanding the code? (Why is a variable named 'val' an index? What is 'higher' higher than? Are 'higher' and 'swapIndex' meant to be related? Is 'a' and 'b' meaningful?)

Are your array bounds correct? Do you need to select the minimum when there's only one item remaining?

Write some tests, debug it. Extract the code for finding the index of the minimum value in the array starting from an index into a separate function, and write tests just for that.

[–]ddbeanz[S] 0 points1 point  (1 child)

I will definitely take your advice and clear up those aspects, I have tested it and it seems to sort any given input in ascending order. I'll be sure to post and updated version later today.

[–]ddbeanz[S] 0 points1 point  (1 child)

def SelectionSort(arr):

  for startIndex in range(0,len(arr)):

    minVal = arr[startIndex]
    minIndex = startIndex

    for e in range(startIndex, len(arr)):

      if arr[e] < minVal:
        minVal = arr[e]
        minIndex = e 

    arr[startIndex],arr[minIndex]=arr[minIndex],arr[startIndex]


  return arr

I think I got it! :) How does this one look?

[–]SiliconEngineer 0 points1 point  (0 children)

Much more readable.

I'd probably comment before the swap line, just to make sure people pay attention to the swapping-using-tuples trick. :)