Java quick sort algorithm example

Quicksort sort

Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays.

Quicksort steps:

  • Pick an element, called a pivot, from the array.
  • Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  • Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

The base case of the recursion is arrays of size zero or one, which are in order by definition, so they never need to be sorted.

Example

package com.w3spoint;
 
public class Test { 
	int partition(int arr[], int low, int high) { 
		int pivot = arr[high]; 
		int i = (low-1); 
		for (int j=low; j<high; j++) { 
			if (arr[j] < pivot) { 
				i++; 
 
				int temp = arr[i]; 
				arr[i] = arr[j]; 
				arr[j] = temp; 
			} 
		} 
 
		int temp = arr[i+1]; 
		arr[i+1] = arr[high]; 
		arr[high] = temp; 
 
		return i+1; 
	} 
 
	void sort(int arr[], int low, int high) { 
		if (low < high) { 
			int pi = partition(arr, low, high); 
 
			sort(arr, low, pi-1); 
			sort(arr, pi+1, high); 
		} 
	} 
 
	void printArray(int arr[]) { 
		for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            if(i != arr.length-1){
            	System.out.print(", ");
            }
        }
        System.out.println("\n");
	} 
 
	public static void main(String args[]) { 
	        Test testObject = new Test(); 
		int arr[] = {9, -3, 5, 2, 6, 8, -6, 1, 3};
		System.out.println("Given array: "); 
		testObject.printArray(arr); 
 
		int arrLength = arr.length; 
		testObject.sort(arr, 0, arrLength-1); 
 
		System.out.println("Sorted array: "); 
		testObject.printArray(arr); 
	} 
}

Output

Given array:
9, -3, 5, 2, 6, 8, -6, 1, 3
 
Sorted array:
-6, -3, 1, 2, 3, 5, 6, 8, 9
Please follow and like us:
Content Protection by DMCA.com