diff --git a/Pseudocode/Sorting/Quicksort.md b/Pseudocode/Sorting/Quicksort.md new file mode 100644 index 0000000000000000000000000000000000000000..f97d2b31ac7199515143c73e1ed177e2943f1ff3 --- /dev/null +++ b/Pseudocode/Sorting/Quicksort.md @@ -0,0 +1,45 @@ +# Quicksort +## Complexity of O(`nlog(n)`) + +The best pivot creates partitions of equal length (or lengths differing by 1). + +The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). + +The run-time of Quicksort ranges from O(n log n) with the best pivots, to O(n^2) with the worst pivots, where ` n` is the number of elements in the array. + +A simple version of Quicksort is as follows: +``` +function quicksort(array) + less, equal, greater := three empty arrays + if length(array) > 1 + pivot := select any element of array + for each x in array + if x < pivot then add x to less + if x = pivot then add x to equal + if x > pivot then add x to greater + quicksort(less) + quicksort(greater) + array := concatenate(less, equal, greater) + ``` +A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. +``` +function quicksort(array) + if length(array) > 1 + pivot := select any element of array + left := first index of array + right := last index of array + while left ≤ right + while array[left] < pivot + left := left + 1 + while array[right] > pivot + right := right - 1 + if left ≤ right + swap array[left] with array[right] + left := left + 1 + right := right - 1 + quicksort(array from first index to right) + quicksort(array from left to last index) + ``` +Quicksort is often compared to Mergesort as they both have an average time complexity of O(nlogn). According to the perldoc: +> On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times. +