Implement Various Types of Partitions in Quick Sort in Java
Last Updated :
02 Sep, 2024
Quicksort is a Divide and Conquer Algorithm that is used for sorting the elements. In this algorithm, we choose a pivot and partitions the given array according to the pivot. Quicksort algorithm is a mostly used algorithm because this algorithm is cache-friendly and performs in-place sorting of the elements means no extra space requires for sorting the elements.
Note:
Quicksort algorithm is generally unstable algorithm because quick sort cannot be able to maintain the relative
order of the elements.
Three partitions are possible for the Quicksort algorithm:
- Naive partition: In this partition helps to maintain the relative order of the elements but this partition takes O(n) extra space.
- Lomuto partition: In this partition, The last element chooses as a pivot in this partition. The pivot acquires its required position after partition but more comparison takes place in this partition.
- Hoare's partition: In this partition, The first element chooses as a pivot in this partition. The pivot displaces its required position after partition but less comparison takes place as compared to the Lomuto partition.
1. Naive partition
Algorithm:
Naivepartition(arr[],l,r)
1. Make a Temporary array temp[r-l+1] length
2. Choose last element as a pivot element
3. Run two loops:
-> Store all the elements in the temp array that are less than pivot element
-> Store the pivot element
-> Store all the elements in the temp array that are greater than pivot element.
4.Update all the elements of arr[] with the temp[] array
QuickSort(arr[], l, r)
If r > l
1. Find the partition point of the array
m = Naivepartition(a,l,r)
2. Call Quicksort for less than partition point
Call Quicksort(arr, l, m-1)
3. Call Quicksort for greater than the partition point
Call Quicksort(arr, m+1, r)
Java
// Java program to demonstrate the naive partition
// in quick sort
import java.io.*;
import java.util.*;
public class GFG {
static int partition(int a[], int start, int high) {
// Choose the last element as the pivot
int pivot = a[high];
// Index of the smaller element
int i = start - 1;
// Rearrange elements based on pivot
for (int j = start; j < high; j++) {
if (a[j] < pivot) {
i++;
// Swap a[i] and a[j]
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
// Place the pivot in the correct position
int temp = a[i + 1];
a[i + 1] = a[high];
a[high] = temp;
return i + 1;
}
static void quicksort(int numbers[], int start, int end) {
if (start < end) {
int point = partition(numbers, start, end);
quicksort(numbers, start, point - 1);
quicksort(numbers, point + 1, end);
}
}
// Function to print the array
static void print(int numbers[]) {
for (int a : numbers) {
System.out.print(a + " ");
}
System.out.println();
}
public static void main(String[] args) {
int numbers[] = { 3, 2, 1, 78, 9798, 97 };
// Rearrange using quicksort
quicksort(numbers, 0, numbers.length - 1);
print(numbers);
}
}
2. Lomuto partition
- Lomuto’s Partition Algorithm (unstable algorithm)
Lomutopartition(arr[], lo, hi)
pivot = arr[hi]
i = lo // place for swapping
for j := lo to hi – 1 do
if arr[j] <= pivot then
swap arr[i] with arr[j]
i = i + 1
swap arr[i] with arr[hi]
return i
QuickSort(arr[], l, r)
If r > l
1. Find the partition point of the array
m =Lomutopartition(a,l,r)
2. Call Quicksort for less than partition point
Call Quicksort(arr, l, m-1)
3. Call Quicksort for greater than the partition point
Call Quicksort(arr, m+1, r)
Java
// Java program to demonstrate the Lomuto partition
// in quick sort
import java.util.*;
public class GFG {
static int sort(int numbers[], int start, int last)
{
int pivot = numbers[last];
int index = start - 1;
int temp = 0;
for (int i = start; i < last; ++i)
{
if (numbers[i] < pivot) {
++index;
// swap the position
temp = numbers[index];
numbers[index] = numbers[i];
numbers[i] = temp;
}
}
int pivotposition = ++index;
temp = numbers[index];
numbers[index] = pivot;
numbers[last] = temp;
return pivotposition;
}
static void quicksort(int numbers[], int start, int end)
{
if (start < end)
{
int pivot_position = sort(numbers, start, end);
quicksort(numbers, start, pivot_position - 1);
quicksort(numbers, pivot_position + 1, end);
}
}
static void print(int numbers[])
{
for (int a : numbers) {
System.out.print(a + " ");
}
}
public static void main(String[] args)
{
int numbers[] = { 4, 5, 1, 2, 4, 5, 6 };
quicksort(numbers, 0, numbers.length - 1);
print(numbers);
}
}
3. Hoare's Partition
Hoare’s Partition Scheme works by initializing two indexes that start at two ends, the two indexes move toward each other until an inversion is (A smaller value on the left side and a greater value on the right side) found. When an inversion is found, two values are swapped and the process is repeated.
Algorithm:
Hoarepartition(arr[], lo, hi)
pivot = arr[lo]
i = lo - 1 // Initialize left index
j = hi + 1 // Initialize right index
// Find a value in left side greater
// than pivot
do
i = i + 1
while arr[i] < pivot
// Find a value in right side smaller
// than pivot
do
j--;
while (arr[j] > pivot);
if i >= j then
return j
swap arr[i] with arr[j]
QuickSort(arr[], l, r)
If r > l
1. Find the partition point of the array
m =Hoarepartition(a,l,r)
2. Call Quicksort for less than partition point
Call Quicksort(arr, l, m)
3. Call Quicksort for greater than the partition point
Call Quicksort(arr, m+1, r)
Java
// Java implementation of QuickSort
// using Hoare's partition scheme
import java.io.*;
class GFG {
// This function takes first element as pivot, and
// places all the elements smaller than the pivot on the
// left side and all the elements greater than the pivot
// on the right side. It returns the index of the last
// element on the smaller side
static int partition(int[] arr, int low, int high)
{
int pivot = arr[low];
int i = low - 1, j = high + 1;
while (true)
{
// Find leftmost element greater
// than or equal to pivot
do {
i++;
} while (arr[i] < pivot);
// Find rightmost element smaller
// than or equal to pivot
do {
j--;
} while (arr[j] > pivot);
// If two pointers met.
if (i >= j)
return j;
// swap(arr[i], arr[j]);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// The main function that
// implements QuickSort
// arr[] --> Array to be sorted,
// low --> Starting index,
// high --> Ending index
static void quickSort(int[] arr, int low, int high)
{
if (low < high) {
// pi is partitioning index,
// arr[p] is now at right place
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi);
quickSort(arr, pi + 1, high);
}
}
// Function to print an array
static void printArray(int[] arr, int n)
{
for (int i = 0; i < n; ++i)
System.out.print(" " + arr[i]);
System.out.println();
}
// Driver Code
static public void main(String[] args)
{
int[] arr = { 10, 17, 18, 9, 11, 15 };
int n = arr.length;
quickSort(arr, 0, n - 1);
printArray(arr, n);
}
}
Similar Reads
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Time and Space Complexity Analysis of Quick Sort The time complexity of Quick Sort is O(n log n) on average case, but can become O(n^2) in the worst-case. The space complexity of Quick Sort in the best case is O(log n), while in the worst-case scenario, it becomes O(n) due to unbalanced partitioning causing a skewed recursion tree that requires a
4 min read
Application and uses of Quicksort Quicksort: Quick sort is a Divide Conquer algorithm and the fastest sorting algorithm. In quick sort, it creates two empty arrays to hold elements less than the pivot element and the element greater than the pivot element and then recursively sort the sub-arrays. There are many versions of Quicksort
2 min read
QuickSort using different languages
Iterative QuickSort
Different implementations of QuickSort
QuickSort using Random PivotingIn this article, we will discuss how to implement QuickSort using random pivoting. In QuickSort we first partition the array in place such that all elements to the left of the pivot element are smaller, while all elements to the right of the pivot are greater than the pivot. Then we recursively call
15+ min read
QuickSort Tail Call Optimization (Reducing worst case space to Log n )Prerequisite : Tail Call EliminationIn QuickSort, partition function is in-place, but we need extra space for recursive function calls. A simple implementation of QuickSort makes two calls to itself and in worst case requires O(n) space on function call stack. The worst case happens when the selecte
11 min read
Implement Quicksort with first element as pivotQuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the pivot. There are many different versions of quickSort that pick the pivot in different ways. Always pick the first element as a pivot.Always pick the last element as a pivot.Pick a
13 min read
Advanced Quick Sort (Hybrid Algorithm)Prerequisites: Insertion Sort, Quick Sort, Selection SortIn this article, a Hybrid algorithm with the combination of quick sort and insertion sort is implemented. As the name suggests, the Hybrid algorithm combines more than one algorithm. Why Hybrid algorithm: Quicksort algorithm is efficient if th
9 min read
Quick Sort using Multi-threadingQuickSort is a popular sorting technique based on divide and conquer algorithm. In this technique, an element is chosen as a pivot and the array is partitioned around it. The target of partition is, given an array and an element x of the array as a pivot, put x at its correct position in a sorted ar
9 min read
Stable QuickSortA sorting algorithm is said to be stable if it maintains the relative order of records in the case of equality of keys.Input : (1, 5), (3, 2) (1, 2) (5, 4) (6, 4) We need to sort key-value pairs in the increasing order of keys of first digit There are two possible solution for the two pairs where th
9 min read
Dual pivot QuicksortAs we know, the single pivot quick sort takes a pivot from one of the ends of the array and partitioning the array, so that all elements are left to the pivot are less than or equal to the pivot, and all elements that are right to the pivot are greater than the pivot.The idea of dual pivot quick sor
10 min read
3-Way QuickSort (Dutch National Flag)In simple QuickSort algorithm, we select an element as pivot, partition the array around a pivot and recur for subarrays on the left and right of the pivot. Consider an array which has many redundant elements. For example, {1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4}. If 4 is picked as
15+ min read
Visualization of QuickSort
Partitions in QuickSort
Some problems on QuickSort
Is Quick Sort Algorithm Adaptive or not Adaptive sorting algorithms are designed to take advantage of existing order in the input data. This means, if the array is already sorted or partially sorted, an adaptive algorithm will recognize that and sort the array faster than it would for a completely random array.Quick Sort is not an adaptiv
6 min read