Commit 9d7d111e authored by Ilya Prokhorov's avatar Ilya Prokhorov

Multithreaded mergesort implemented

parent a94505ff
import Dispatch
import Foundation
extension Array {
func item<T>(at index: Int) -> T? {
guard index >= 0 else { return nil }
guard index <= count - 1 else { return nil }
return self[index] as? T
}
}
func mergeSort<T: Comparable>(lhsList: [T], rhsList: [T]) -> [T] {
var outputList: [T] = []
var rhsList = rhsList
var lhsList = lhsList
while let lhsFirst = lhsList.first {
if let rhsFirst = rhsList.first, rhsFirst < lhsFirst {
outputList.append(rhsFirst)
rhsList.removeFirst()
}
else {
outputList.append(lhsFirst)
lhsList.removeFirst()
}
}
outputList.append(contentsOf: rhsList)
return outputList
}
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 {
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 sorted = mergeSort(lhsList: lhs, rhsList: rhs)
arrayDispatch.async {
if sorted.count > 0 {
outputAtoms.append(sorted)
}
group.leave()
}
}
}
group.wait()
atoms = outputAtoms
outputAtoms.removeAll()
}
return atoms
}
func divideIntoAtoms<T: Comparable>(list: [T]) -> [[T]] {
var outputList: [[T]] = []
for atom in list {
outputList.append([atom])
}
return outputList
}
let list = ["John", "Alice", "Mike", "#1", "Артем", "20", "60"]
var atoms = divideIntoAtoms(list: list)
atoms = merge(atoms: atoms)
print(list)
print(atoms)
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