-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQuickSort.swift
More file actions
77 lines (51 loc) · 1.85 KB
/
Copy pathQuickSort.swift
File metadata and controls
77 lines (51 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
// QuickSort.swift
// AdvancedDataStructures
//
// Created by Vladislav Fitc on 02.11.17.
// Copyright © 2017 Fitc. All rights reserved.
//
import Foundation
class QuickSort<E: Comparable>: SortAlgorithm {
typealias GetPivot<Element> = (ArraySlice<Element>) -> Element where Element: Comparable
typealias Element = E
let input: [Element]
var output: [Element] = []
var getPivot: GetPivot<Element>
init(input: [Element], getPivot: @escaping GetPivot<Element>) {
self.input = input
self.getPivot = getPivot
}
private func partition(array: inout ArraySlice<Element>) -> Int {
let pivot = getPivot(array)
var leftPointer = array.startIndex
var rightPointer = array.endIndex - 1
while leftPointer <= rightPointer {
while array[leftPointer] < pivot {
leftPointer = leftPointer + 1
}
while array[rightPointer] > pivot {
rightPointer = rightPointer - 1
}
if leftPointer <= rightPointer {
array.swapAt(leftPointer, rightPointer)
leftPointer = leftPointer + 1
rightPointer = rightPointer - 1
}
}
return rightPointer
}
private func sliceQSort(array: inout ArraySlice<Element>) {
if array.count == 0 || array.count == 1 {
return
}
let pivotIndex = partition(array: &array)
sliceQSort(array: &array[...pivotIndex])
sliceQSort(array: &array[(pivotIndex+1)...])
}
func perform() {
var slice = ArraySlice(input)
sliceQSort(array: &slice)
output = Array(slice)
}
}