Created
May 19, 2020 02:44
-
-
Save clc80/c5f87cb7014c229c5bd1790102745690 to your computer and use it in GitHub Desktop.
Function to show bubble sort
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
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