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:
9191
9292``` swift
9393func 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
100100 }
101101 }
102- return a
102+ return sortedArray
103103}
104104
105105
@@ -154,17 +154,17 @@ In code that looks like this:
154154
155155``` swift
156156func 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
164164 }
165- a[y ] = temp // 2
165+ sortedArray[currentIndex ] = temp // 2
166166 }
167- return a
167+ return sortedArray
168168}
169169```
170170
You can’t perform that action at this time.
0 commit comments