Update 05_quicksort.swift (#257)

This commit is contained in:
TheDexire
2023-07-19 21:56:17 +06:00
committed by GitHub
parent 7620449322
commit 4dddd5aa83

View File

@@ -2,20 +2,17 @@ import Foundation
//The following implementation of quick sort is little more classic than described in the book, but we have two use this one because of some slice feature limitation with array on Swift 3. Main concept is the same //The following implementation of quick sort is little more classic than described in the book, but we have two use this one because of some slice feature limitation with array on Swift 3. Main concept is the same
func quicksort <T : Comparable> (_ array : [T]) -> [T] { func quicksort <T : Comparable> (_ array : [T]) -> [T] {
if (array.count < 2) { // base case, arrays with 0 or 1 element are already "sorted"
// base case, arrays with 0 or 1 element are already "sorted" guard array.count > 1 else { return array }
return array // recursive case
} else { let pivot = array[0]
// recursive case // sub-array of all the elements less than the pivot
let pivot = array[0] let less = array.filter { $0 < pivot }
// sub-array of all the elements less than the pivot // sub-array of all the elements equal to the pivot
let less = array.filter { $0 < pivot } let equal = array.filter { $0 == pivot }
// sub-array of all the elements equal to the pivot // sub-array of all the elements greater than the pivot
let equal = array.filter { $0 == pivot } let greater = array.filter { $0 > pivot }
// sub-array of all the elements greater than the pivot return quicksort(less) + equal + quicksort(greater)
let greater = array.filter { $0 > pivot }
return quicksort(less) + equal + quicksort(greater)
}
} }
print(quicksort([1, 5, 10, 25, 16, 1])) // => [1, 1, 5, 10, 16, 25] print(quicksort([1, 5, 10, 25, 16, 1])) // => [1, 1, 5, 10, 16, 25]