Created
June 30, 2015 07:00
-
-
Save onevcat/8ca318c1fc41ae064539 to your computer and use it in GitHub Desktop.
Quick sort of Swift
This file contains 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 | |
var randomNumbers = [42, 12, 88, 62, 63, 56, 1, 77, 88, 97, 97, 20, 45, 91, 62, 2, 15, 31, 59, 5] | |
func partition(inout v: [Int], left: Int, right: Int) -> Int { | |
var i = left | |
for j in (left + 1) ... right { | |
if v[j] < v[left] { | |
i += 1 | |
(v[i], v[j]) = (v[j], v[i]) | |
} | |
} | |
(v[i], v[left]) = (v[left], v[i]) | |
print(v) | |
return i | |
} | |
func quicksort(inout v: [Int], left: Int, right: Int) { | |
if right > left { | |
let pivotIndex = partition(&v, left: left, right: right) | |
quicksort(&v, left: left, right: pivotIndex - 1) | |
quicksort(&v, left: pivotIndex + 1, right: right) | |
} | |
} | |
quicksort(&randomNumbers, left: 0, right: randomNumbers.count-1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment