Last active
March 6, 2018 04:27
-
-
Save KyNorthstar/6b09d7c087f0e7e1d5fdf00cac79815f to your computer and use it in GitHub Desktop.
General-use Quicksort in Swift
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
/// Uses quicksort with the Lomuto partition scheme. | |
/// | |
/// By Ben Leggiero, written on 2018-03-05. Copyright BH-0-PD | |
/// https://github.com/BlueHuskyStudios/Licenses/blob/master/Licenses/BH-0-PD.txt | |
struct QuickSorter { | |
/// Performs a quicksort with Lomuto partition using the given array and returns the result | |
func quicksorting<C: Comparable>(_ unsorted: [C]) -> [C] { | |
var arrayCopy = unsorted | |
QuickSorter.quicksort(&arrayCopy) | |
return arrayCopy | |
} | |
/// Performs a quicksort with Lomuto partition by mutating the given array | |
static func quicksort<C: Comparable>(_ unsorted: inout [C]) { | |
quicksort(&unsorted, first: 0, last: unsorted.count - 1) | |
} | |
/// Quicksort basic algorithm as published on Wikipedia | |
/// https://en.wikipedia.org/wiki/Quicksort?oldid=827460998#Lomuto_partition_scheme | |
private static func quicksort<C: Comparable>(_ array: inout [C], first: Int, last: Int) { | |
if first < last { | |
let p = partition(&array, first: first, last: last) | |
quicksort(&array, first: first, last: p - 1) | |
quicksort(&array, first: p + 1, last: last) | |
} | |
} | |
/// Quicksort basic algorithm as published on Wikipedia | |
/// https://en.wikipedia.org/wiki/Quicksort?oldid=827460998#Lomuto_partition_scheme | |
private static func partition<C: Comparable>(_ array: inout [C], first: Int, last: Int) -> Int { | |
let pivot = array[last] | |
var i = first - 1 | |
for j in first..<last { | |
if array[j] < pivot { | |
i = i + 1 | |
array.swapAt(i, j) | |
} | |
} | |
array.swapAt(i + 1, last) | |
return i + 1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment