Quicksort | ![]() ![]() |
Quicksort is one of the fastest and simplest sorting algorithms [Hoa 62]. It works recursively by a divide-and-conquer strategy.
Idea
First, the sequence to be sorted a is partitioned into two parts, such that all elements of the first part b are less than or equal to all elements of the second part c (divide). Then the two parts are sorted separately by recursive application of the same procedure (conquer). Recombination of the two parts yields the sorted sequence (combine). Figure 1 illustrates this approach.
| |
Figure 1: Quicksort(n) | |
The first step of the partition procedure is choosing a comparison element x. All elements of the sequence that are less than x are placed in the first part, all elements greater than x are placed in the second part. For elements equal to x it does not matter into which part they come. In the following algorithm it may also happen that an element equal to x remains between the two parts.
Algorithm Partition | |
Input: | sequence a0, ..., an-1 with n elements |
Output: | permutation of the sequence such that all elements a0, ..., aj are less than or equal to all elements ai, ..., an-1 (i > j) |
Method: |
|
After partitioning the sequence, quicksort treats the two parts recursively by the same procedure. The recursion ends whenever a part consists of one element only.