Commit 6ec0ba5f authored by Ilya Prokhorov's avatar Ilya Prokhorov

Multithreaded mergesort implementation

parent 9d7d111e
......@@ -30,32 +30,24 @@ func mergeSort<T: Comparable>(lhsList: [T], rhsList: [T]) -> [T] {
}
func merge<T: Comparable>(atoms: [[T]]) -> [[T]] {
var atoms = atoms
let group = DispatchGroup()
let arrayDispatch = DispatchQueue(label: "array-lock")
var outputAtoms: [[T]] = []
while atoms.count > 1 {
for i in 0..<atoms.count {
for i in stride(from: 0, to: atoms.count, by: 2) {
group.enter()
DispatchQueue.global(qos: .default).async {
let lhs: [T] = atoms.item(at: i * 2) ?? []
let rhs: [T] = atoms.item(at: i * 2 + 1) ?? []
let lhs: [T] = atoms.item(at: i) ?? []
let rhs: [T] = atoms.item(at: i + 1) ?? []
let sorted = mergeSort(lhsList: lhs, rhsList: rhs)
arrayDispatch.async {
if sorted.count > 0 {
outputAtoms.append(sorted)
}
outputAtoms.append(sorted)
group.leave()
}
}
}
group.wait()
atoms = outputAtoms
outputAtoms.removeAll()
......@@ -72,10 +64,10 @@ func divideIntoAtoms<T: Comparable>(list: [T]) -> [[T]] {
return outputList
}
let list = ["John", "Alice", "Mike", "#1", "Артем", "20", "60"]
let list = ["John", "Alice", "Mike", "#1", "Артем", "20", "60", "60", "DoubleTrouble"]
var atoms = divideIntoAtoms(list: list)
atoms = merge(atoms: atoms)
print(list)
print(atoms)
print(atoms.first ?? "-")
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment