English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to implement the quick sort algorithm in Java.
Before learning the quick sort algorithm in Java, please make sure you understand the working principle of the quick sort algorithm.
//Java quick sort import java.util.Arrays; class Main { //Divide the array according to the data axis int partition(int array[], int low, int high) { //Choose the last element as the axis int pivot = array[high]; //Initialize the second pointer int i = (low - 1); //Place the elements less than the axis on the left //The pivot on the right of the pivot on the right for (int j = low; j < high; j++) { //Compare all elements with pivot //Swap the elements greater than pivot //The element is less than pivot //Sort in descending order // if (array[j] >= pivot) if (array[j] <= pivot) { //The second pointer increments. //Replace the smaller element with the larger element i++; int temp = array[i]; array[i] = array[j]; array[j] = temp; } } //Therefore, the elements on the left are smaller //The elements on the right are greater than pivot int temp = array[i + 1]; array[i + 1] = array[high]; array[high] = temp; return (i + 1); } void quickSort(int array[], int low, int high) { if (low < high) { //Choose the axis position and place all elements smaller //The left axis is greater than the axis, the right axis is greater than the axis int pi = partition(array, low, high); //Sort the elements on the left side of the axis quickSort(array, low, pi - 1); //Sort the elements on the right side of the axis quickSort(array, pi + 1, high); } } public static void main(String args[]) { //Create an unsorted array int[] data = { 8, 7, 2, 1, 0, 9, 6 }; int size = data.length; //Create an object of the Main class Main qs = new Main(); //Pass the first and last index to the array qs.quickSort(data, 0, size - 1); System.out.println("Sorted Array: "); System.out.println(Arrays.toString(data)); } }
Output1
Unsorted Array: [8, 7, 2, 1, 0, 9, 6] Sorted Array: [0, 1, 2, 6, 7, 8, 9]
In this case, the elements of the array are sorted in ascending order. If we want to sort the elements in descending order, we can change the code in the for loop of the Partition() method as follows:
//Change the less than symbol to greater than if (array[j] >= pivot) {