Created
January 25, 2018 21:10
-
-
Save nthState/e16f09d9af9962c2e5bbe812ccc8f2ae to your computer and use it in GitHub Desktop.
Bubble/Quick 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
//: Playground - noun: a place where people can play | |
import UIKit | |
func quickSort(ls:[Int]) -> [Int] | |
{ | |
guard ls.count > 1 else { return ls } | |
let pivot = ls[ls.count/2] | |
let less = ls.filter({ $0 < pivot }) | |
let equal = ls.filter({ $0 == pivot }) | |
let greater = ls.filter({ $0 > pivot }) | |
return quickSort(ls: less) + equal + quickSort(ls: greater) | |
} | |
var items = [375,3,6,2,4,6,8,4,2,4,6] | |
let sorted = quickSort(ls: items) | |
func bubbleSort( ls:inout [Int]) | |
{ | |
while true | |
{ | |
var sorted = false | |
for i in 1..<ls.count | |
{ | |
if ls[i] < ls[i - 1] | |
{ | |
let temp = ls[i] | |
ls[i] = ls[i - 1] | |
ls[i - 1] = temp | |
sorted = true | |
} | |
} | |
if !sorted | |
{ | |
break | |
} | |
} | |
} | |
bubbleSort(ls: &items) | |
print(items) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment