Skip to content

Instantly share code, notes, and snippets.

@shanecowherd
Created October 18, 2022 18:18
Show Gist options
  • Save shanecowherd/cd6492e68e9e3df362f691508e34c5a2 to your computer and use it in GitHub Desktop.
Save shanecowherd/cd6492e68e9e3df362f691508e34c5a2 to your computer and use it in GitHub Desktop.
import UIKit
var unsortedNumbers = [1,5,7,9,2,4,7];
func bubbleSort(unsortedNumbers: inout [Int]) -> [Int] {
for _ in unsortedNumbers {
for (idx, _) in unsortedNumbers.enumerated() {
guard idx + 1 < unsortedNumbers.count else {
continue
}
let rhs = unsortedNumbers[idx + 1]
let lhs = unsortedNumbers[idx]
if rhs < lhs {
unsortedNumbers[idx + 1] = lhs
unsortedNumbers[idx] = rhs
}
}
}
return unsortedNumbers
}
bubbleSort(unsortedNumbers: &unsortedNumbers)
// Now with while instead of a for loop.
var unsortedNumbers2 = [1,5,7,9,2,4,7];
func bubbleSort2(unsortedNumbers: inout [Int]) -> [Int] {
var loopIterations = unsortedNumbers.count - 1
var currentIndex = 0
while (loopIterations > 0) {
while (currentIndex < loopIterations) {
if unsortedNumbers[currentIndex] > unsortedNumbers[currentIndex + 1] {
let placeholder = unsortedNumbers[currentIndex + 1]
unsortedNumbers[currentIndex + 1] = unsortedNumbers[currentIndex]
unsortedNumbers[currentIndex] = placeholder
}
currentIndex += 1
}
currentIndex = 0
loopIterations -= 1
}
return unsortedNumbers
}
bubbleSort2(unsortedNumbers: &unsortedNumbers2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment