Data Structures & Algorithms in Swift · Sorting Algorithms | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/977854-data-structures-algorithms-in-swift/lessons/7

Hi, in the demonstration regarding the Selection Sort, you have swapped the last number “3” within the index with the first number “9” but in the formula the loop begins with “for current in 0…<(array.count - 1)” I couldn’t understand the connection between the demonstration and the formulas of both bubble and selection sort.

@jessycatterwaul @catie Can you please help with this when you get a chance? Thank you - much appreciated! :]

Hi! For selection sort, it’s true that the range, 0..(<array.count -1), doesn’t include the last element in the array. But the range used in the nested loop, (current + 1)..<array.count, does include the last element.

So in the demonstration, when we are iteratively comparing the card values, that’s all taking place within the nested loop. The swap happens when the nested loop is finished, if it needs to happen at all.

Hope that helps!

Am I missing something?
The sort functions start with

guard array.count >= 2 else { return array }

If an array to be sorted were [1,0] its count would be 2 and thus returned unsorted.

Hi Matt! That guard statement is checking if the count is greater than or equal to 2. So an array like [1, 0] with two elements would be sorted.

Helps when I read it correctly :upside_down_face:. I saw it as less than or equal to. Thank you :hugs:

1 Like