Quicksort Algorithm
Quicksort Algorithm
While dividing the array, the pivot element should be positioned in such a
way that elements less than pivot are kept on the left side and elements
greater than pivot are on the right side of the pivot.
2. The left and right subarrays are also divided using the same approach. This
process continues until each subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined
to form a sorted array.
Select a pivot
element
2. Rearrange the Array
Now the elements of the array are rearranged so that elements that are
smaller than the pivot are put on the left and the elements greater than the
pivot are put on the right.
1. A pointer is fixed at the pivot element. The pivot element is compared with
the elements beginning from the first index.
Comparison of
pivot element with element beginning from the first index
2. If the element is greater than the pivot element, a second pointer is set for
that element. If
the element is greater than the pivot element, a second pointer is set for
that element.
3. Now, pivot is compared with other elements. If an element smaller than the
pivot element is reached, the smaller element is swapped with the greater
element found earlier.
Pivot is compared
with other elements.
4. Again, the process is repeated to set the next greater element as the
second pointer. And, swap it with another smaller element.
The process is
repeated to set the next greater element as the second pointer.
3. Divide Subarrays
Pivot elements are again chosen for the left and the right sub-parts
separately. And, step 2 is repeated.
#include <iostream>
using namespace std;
// Driver code
int main() {
int data[] = {8, 7, 6, 1, 0, 9, 2};
int n = sizeof(data) / sizeof(data[0]);