DSA - Sorting - Quick Sort

Introduction The quick sort is an efficient sorting algorithm commonly used widely in production. Quick sort is a divide-and-conquer algorithm. It works by selecting a pivot from the array and partitioning the other elements into two subarrays. source Code example // Sorts a (portion of an) array, divides it into partitions, then sorts those func quickSort(array: inout [Int], low: Int, high: Int) { // Ensure indices are in correct order if low < high { // Partition array and get the pivot index let p = partition(array: &array, low: low, high: high) // Sort the two partitions quickSort(array: &array, low: low, high: p - 1) // Left side of pivot quickSort(array: &array, low: p + 1, high: high) // Right side of pivot } } // Divides array into two partitions func partition(array: inout [Int], low: Int, high: Int) -> Int { let pivot = array[high] // Choose the last element as the pivot // Temporary pivot index var i = low for j in low ....

October 19, 2024 · 2 min · Dmytro Chumakov