Quick Sort - O(n log n) average time

suggest change

Quicksort is a divide-and-conquer sort. Its average time is O(n log n). The worst case, already-partitioned input with this pivot choice, is O(n²). Quicksort divides an array into values below the pivot and values above it, then sorts those parts recursively.

The steps are:

  1. Pick an element, called a pivot, from the array.
  2. Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.
extension Array where Element: Comparable {
mutating func quickSort() -> Array<Element> {

func qSort(start startIndex: Int, _ pivot: Int) {
    
    if (startIndex < pivot) {
        let iPivot = qPartition(start: startIndex, pivot)
        qSort(start: startIndex, iPivot - 1)
        qSort(start: iPivot + 1, pivot)
    }
}
qSort(start: 0, self.endIndex - 1)
return self

}

mutating func qPartition(start startIndex: Int, _ pivot: Int) -> Int {

var wallIndex: Int = startIndex

//compare range with pivot
for currentIndex in wallIndex..<pivot {
    
    if self[currentIndex] <= self[pivot] {
        if wallIndex != currentIndex {
            // Swift 4 and later: swapAt. Earlier Swift used swap(&self[i], &self[j]).
            self.swapAt(currentIndex, wallIndex)
        }
        
        //advance wall
        wallIndex += 1
    }
}


//move pivot to final position
if wallIndex != pivot {
    self.swapAt(wallIndex, pivot)
}
return wallIndex
}
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents