How to create a quicksort implementation in swift?

Member

by dana , in category: Third Party Scripts , 14 days ago

How to create a quicksort implementation in swift?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 13 days 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.