File tree Expand file tree Collapse file tree 1 file changed +16
-16
lines changed Expand file tree Collapse file tree 1 file changed +16
-16
lines changed Original file line number Diff line number Diff line change @@ -91,15 +91,15 @@ Here is an implementation of insertion sort in Swift:
91
91
92
92
``` swift
93
93
func insertionSort (_ array : [Int ]) -> [Int ] {
94
- var a = array // 1
95
- for x in 1 ..< a .count { // 2
96
- var y = x
97
- while y > 0 && a[y ] < a[y - 1 ] { // 3
98
- a .swapAt (y - 1 , y )
99
- y -= 1
94
+ var sortedArray = array // 1
95
+ for index in 1 ..< sortedArray .count { // 2
96
+ var currentIndex = index
97
+ while currentIndex > 0 && sortedArray[currentIndex ] < sortedArray[currentIndex - 1 ] { // 3
98
+ sortedArray .swapAt (currentIndex - 1 , currentIndex )
99
+ currentIndex -= 1
100
100
}
101
101
}
102
- return a
102
+ return sortedArray
103
103
}
104
104
105
105
@@ -154,17 +154,17 @@ In code that looks like this:
154
154
155
155
``` swift
156
156
func insertionSort (_ array : [Int ]) -> [Int ] {
157
- var a = array
158
- for x in 1 ..< a .count {
159
- var y = x
160
- let temp = a[y ]
161
- while y > 0 && temp < a[y - 1 ] {
162
- a[y ] = a[y - 1 ] // 1
163
- y -= 1
157
+ var sortedArray = array
158
+ for index in 1 ..< sortedArray .count {
159
+ var currentIndex = index
160
+ let temp = sortedArray[currentIndex ]
161
+ while currentIndex > 0 && temp < sortedArray[currentIndex - 1 ] {
162
+ sortedArray[currentIndex ] = sortedArray[currentIndex - 1 ] // 1
163
+ currentIndex -= 1
164
164
}
165
- a[y ] = temp // 2
165
+ sortedArray[currentIndex ] = temp // 2
166
166
}
167
- return a
167
+ return sortedArray
168
168
}
169
169
```
170
170
You can’t perform that action at this time.
0 commit comments