How to create a quicksort implementation in swift?

Member

by dana , in category: Third Party Scripts , 4 months ago

How to create a quicksort implementation in swift?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 4 months ago

@dana 

Here is a simple implementation of quicksort in Swift:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func quicksort<T: Comparable>(_ array: [T]) -> [T] {
    guard array.count > 1 else { return array }
    
    let pivot = array[array.count / 2]
    let less = array.filter { $0 < pivot }
    let equal = array.filter { $0 == pivot }
    let greater = array.filter { $0 > pivot }
    
    return quicksort(less) + equal + quicksort(greater)
}

// Example usage
let array = [5, 2, 9, 3, 7, 1, 8, 6, 4]
let sortedArray = quicksort(array)
print(sortedArray) // [1, 2, 3, 4, 5, 6, 7, 8, 9]


This implementation uses recursion to divide the array into three parts: elements less than the pivot, elements equal to the pivot, and elements greater than the pivot. It then recursively sorts the less and greater arrays and combines them with the equal array to produce the final sorted array.

Related Threads:

How To Compute Pivot Points in Swift?
How to create jwt token in symfony 5?
How To Calculate Chaikin Money Flow (CMF) using Swift?
How to get quicksort depth?
How to obtain the inputs to quicksort?
How to quicksort list of lists in prolog?