Skip to content

Commit eb9424d

Browse files
author
abuzeid ibrahim
committed
rename variables with convenience names
1 parent 3849a1d commit eb9424d

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

Insertion Sort/InsertionSort.swift

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,22 @@
22
///
33
/// - Parameters:
44
/// - array: the array of elements to be sorted
5+
/// - sortedArray: copy the array to save stability
56
/// - isOrderedBefore: returns true if the elements provided are in the corect order
67
/// - Returns: a sorted array containing the same elements
78
func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
8-
guard array.count > 1 else { return array }
9-
10-
var a = array
11-
for x in 1..<a.count {
12-
var y = x
13-
let temp = a[y]
14-
while y > 0 && isOrderedBefore(temp, a[y - 1]) {
15-
a[y] = a[y - 1]
16-
y -= 1
9+
guard array.count > 1 else { return array }
10+
var sortedArray = array
11+
for index in 1..<sortedArray.count {
12+
var currentIndex = index
13+
let temp = sortedArray[currentIndex]
14+
while currentIndex > 0, isOrderedBefore(temp, sortedArray[currentIndex - 1]) {
15+
sortedArray[currentIndex] = sortedArray[currentIndex - 1]
16+
currentIndex -= 1
17+
}
18+
sortedArray[currentIndex] = temp
1719
}
18-
a[y] = temp
19-
}
20-
return a
20+
return sortedArray
2121
}
2222

2323
/// Performs the Insertion sort algorithm to a given array
@@ -27,15 +27,15 @@ func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
2727
func insertionSort<T: Comparable>(_ array: [T]) -> [T] {
2828
guard array.count > 1 else { return array }
2929

30-
var a = array
31-
for x in 1..<a.count {
32-
var y = x
33-
let temp = a[y]
34-
while y > 0 && temp < a[y - 1] {
35-
a[y] = a[y - 1]
36-
y -= 1
30+
var sortedArray = array
31+
for index in 1..<sortedArray.count {
32+
var currentIndex = index
33+
let temp = sortedArray[currentIndex]
34+
while currentIndex > 0, temp < sortedArray[currentIndex - 1] {
35+
sortedArray[currentIndex] = sortedArray[currentIndex - 1]
36+
currentIndex -= 1
3737
}
38-
a[y] = temp
38+
sortedArray[currentIndex] = temp
3939
}
40-
return a
40+
return sortedArray
4141
}

0 commit comments

Comments
 (0)