Skip to content

Commit a892d47

Browse files
authored
Merge pull request #1 from ibrahimHamed/patch-2
Update README.markdown
2 parents e592ed6 + 2718969 commit a892d47

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

Selection Sort/README.markdown

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -59,40 +59,37 @@ The selection sort is an *in-place* sort because everything happens in the same
5959
Here is an implementation of selection sort in Swift:
6060

6161
```swift
62-
func selectionSort(_ array: [Int]) -> [Int] {
63-
guard array.count > 1 else { return array } // 1
62+
func selectionSort(_ array: inout [Int]){ // 1
63+
guard array.count > 1 else { return array } // 2
6464

65-
var a = array // 2
66-
67-
for x in 0 ..< a.count - 1 { // 3
65+
for x in 0 ..< array.count - 1 { // 3
6866

6967
var lowest = x
70-
for y in x + 1 ..< a.count { // 4
71-
if a[y] < a[lowest] {
68+
for y in x + 1 ..< array.count { // 4
69+
if array[y] < array[lowest] {
7270
lowest = y
7371
}
7472
}
7573

7674
if x != lowest { // 5
77-
a.swapAt(x, lowest)
75+
array.swapAt(x, lowest)
7876
}
7977
}
80-
return a
8178
}
8279
```
8380

8481
Put this code in a playground and test it like so:
8582

8683
```swift
8784
let list = [ 10, -1, 3, 9, 2, 27, 8, 5, 1, 3, 0, 26 ]
88-
selectionSort(list)
85+
selectionSort(&list)
8986
```
9087

9188
A step-by-step explanation of how the code works:
9289

93-
1. If the array is empty or only contains a single element, then there is no need to sort.
90+
1. By adding `inout` before the parameter name, you indicate that the function can modify the original array directly.
9491

95-
2. Make a copy of the array. This is necessary because we cannot modify the contents of the `array` parameter directly in Swift. Like the Swift's `sort()` function, the `selectionSort()` function will return a sorted *copy* of the original array.
92+
2. If the array is empty or only contains a single element, then there is no need to sort.
9693

9794
3. There are two loops inside this function. The outer loop looks at each of the elements in the array in turn; this is what moves the `|` bar forward.
9895

0 commit comments

Comments
 (0)