21
loading...
This website collects cookies to deliver better user experience
quicksort()
function as well as the partition()
function. The meat of the algorithm counter-intuitively lives in the partition()
function. It’s responsible for finding the pivot and moving everything to the correct side of the pivot.func partition(arr []int, low, high int) ([]int, int) {
pivot := arr[high]
i := low
for j := low; j < high; j++ {
if arr[j] < pivot {
arr[i], arr[j] = arr[j], arr[i]
i++
}
}
arr[i], arr[high] = arr[high], arr[i]
return arr, i
}
<small id="shcb-language-1"><span>Code language:</span> <span>Go</span> <span>(</span><span>go</span><span>)</span></small>
quickSort()
function is really just a wrapper around the partition function, and it handles the recursive nature of the algorithm.func quickSort(arr []int, low, high int) []int {
if low < high {
var p int
arr, p = partition(arr, low, high)
arr = quickSort(arr, low, p-1)
arr = quickSort(arr, p+1, high)
}
return arr
}`
<small id="shcb-language-2"><span>Code language:</span> <span>Go</span> <span>(</span><span>go</span><span>)</span></small>
fmt.Println(quickSortStart([]int{5, 6, 7, 2, 1, 0))
// prints
// [0, 1, 2, 5, 6, 7]`
<small id="shcb-language-3"><span>Code language:</span> <span>Go</span> <span>(</span><span>go</span><span>)</span></small>
O(n*log(n))
. In the worst case, and assuming we don’t take any steps to protect ourselves, it can break down to O(n^2)
. The partition()
function has a single for-loop that ranges from the lowest index to the highest index in the array. By itself, the partition()
function is O(n)
. The overall complexity of quicksort is dependent on how many times partition()
is called.partition()
is called a total of n
times. In the best case, the pivot is the middle element of each sublist which results in log(n)
calls to partition()
.O(n*log(n))
, it’s Big O complexity is still technically O(n^2)
. We can fix this by altering the algorithm slightly. There are two approaches:O(n)
time.O(1)
time.O(n^2)
time because we are guaranteed to never use the worst item in the partition as the pivot. That said, it can still be slow_er_ because a true median isn’t used.