Skip to content

Instantly share code, notes, and snippets.

@clc80
Created May 19, 2020 02:44
Show Gist options
  • Save clc80/c5f87cb7014c229c5bd1790102745690 to your computer and use it in GitHub Desktop.
Save clc80/c5f87cb7014c229c5bd1790102745690 to your computer and use it in GitHub Desktop.
Function to show bubble sort
import UIKit
func bubbleSort<AnyItem: Comparable>(_ array: [AnyItem] ) -> [AnyItem] {
var newArray = array
var temp: AnyItem
for i in 0..<newArray.count - 1 {
for j in (i + 1)..<newArray.count {
if newArray[i] > newArray[j] {
//swap
temp = newArray[i]
newArray[i] = newArray[j]
newArray[j] = temp
}
}
}
return newArray
}
print(bubbleSort([1, 3, 6, 2, 4, 5]))
print(bubbleSort([1.9, 3.2, 3.6, 2.7, 49, 0.5]))
print(bubbleSort(["apple", "avocado", "apricot", "anchovy", "anchor"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment