From 4dddd5aa830040e9525ba34b30314f6e34560ec8 Mon Sep 17 00:00:00 2001 From: TheDexire <80020807+TheDexire@users.noreply.github.com> Date: Wed, 19 Jul 2023 21:56:17 +0600 Subject: [PATCH] Update 05_quicksort.swift (#257) --- 04_quicksort/swift/05_quicksort.swift | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/04_quicksort/swift/05_quicksort.swift b/04_quicksort/swift/05_quicksort.swift index e017b4d..9449921 100644 --- a/04_quicksort/swift/05_quicksort.swift +++ b/04_quicksort/swift/05_quicksort.swift @@ -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 func quicksort (_ array : [T]) -> [T] { - if (array.count < 2) { - // base case, arrays with 0 or 1 element are already "sorted" - return array - } else { - // recursive case - let pivot = array[0] - // sub-array of all the elements less than the pivot - let less = array.filter { $0 < pivot } - // sub-array of all the elements equal to the pivot - let equal = array.filter { $0 == pivot } - // sub-array of all the elements greater than the pivot - let greater = array.filter { $0 > pivot } - return quicksort(less) + equal + quicksort(greater) - } + // base case, arrays with 0 or 1 element are already "sorted" + guard array.count > 1 else { return array } + // recursive case + let pivot = array[0] + // sub-array of all the elements less than the pivot + let less = array.filter { $0 < pivot } + // sub-array of all the elements equal to the pivot + let equal = array.filter { $0 == pivot } + // sub-array of all the elements greater than the pivot + 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]