Last active
July 4, 2022 19:04
-
-
Save tmdvs/d8edeb9bf26f2f5c3e50 to your computer and use it in GitHub Desktop.
Bubble sort in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An Example of a bubble sort algorithm in Swift | |
// | |
// Essentialy this algorithm will loop through the values up to | |
// the index where we last did a sort (everything above is already in order/sorted) | |
// comparing a one value to the value before it. If the value before it is higher, | |
// swap them, and note the highest swap index. On the next iteration of the loop we | |
// only need to go as high as the previous swap. | |
import Foundation | |
var array = [5,3,4,6,8,2,9,1,7,10,11] | |
var sortedArray = NSMutableArray(array: array) | |
var sortedAboveIndex = array.count // Assume all values are not in order | |
do { | |
var lastSwapIndex = 0 | |
for ( var i = 1; i < sortedAboveIndex; i++ ) { | |
if (sortedArray[i - 1].integerValue > sortedArray[i].integerValue) { | |
sortedArray.exchangeObjectAtIndex(i, withObjectAtIndex: i-1) | |
lastSwapIndex = i | |
} | |
} | |
sortedAboveIndex = lastSwapIndex | |
} while (sortedAboveIndex != 0) | |
// [5, 3, 4, 6, 8, 2, 9, 1, 7, 10, 11] | |
println(array) | |
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] | |
println(sortedArray as Array) |
some touch-ups:
`
var array = [5,3,4,6,8,2,9,1,7,10,11]
var sortedArray = Array(array)
var sortedAboveIndex = array.count // Assume all values are not in order
var lastSwapIndex = 0
//repeat {
for i in 1 ..< sortedAboveIndex {
if ((sortedArray[i - 1] ) > (sortedArray[i] )) {
swap(&sortedArray[i], &sortedArray[i - 1])
lastSwapIndex = i
}
}
sortedAboveIndex = lastSwapIndex
//} while (sortedAboveIndex != 0)
// [5, 3, 4, 6, 8, 2, 9, 1, 7, 10, 11]
print(array)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(sortedArray)`
Swift 3
var array = [5,3,4,6,8,2,9,1,7,10,11]
var sortedArray = NSMutableArray(array: array)
var sortedAboveIndex = array.count
var swaps = 0
repeat {
var lastSwapIndex = 0
for i in 1..<sortedAboveIndex {
if (sortedArray[i - 1] as! Int) > (sortedArray[i] as! Int) {
sortedArray.exchangeObject(at: i, withObjectAt: i-1)
lastSwapIndex = i
swaps += 1
}
}
sortedAboveIndex = lastSwapIndex
} while (sortedAboveIndex != 0)
// [5, 3, 4, 6, 8, 2, 9, 1, 7, 10, 11]
print(array)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(sortedArray as Array)
print("Array is sorted in \(swaps) swaps.")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Getting two warnings on line 18 , C-style for statement and ++ are both deprecated. But otherwise it works like a charm!