English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此示例中,我们将学习在Java中实现快速排序算法。
在学习Java中的快速排序算法之前,请确保您了解快速排序算法的工作原理。
//用Java快速排序 import java.util.Arrays; class Main { //根据数据轴划分数组 int partition(int array[], int low, int high) { //选择最后一个元素作为轴 int pivot = array[high]; //初始化第二个指针 int i = (low - 1); //把小于轴的元素放在左边 //大于枢轴右侧的枢轴 for (int j = low; j < high; j++) { //将所有元素与pivot进行比较 //交换大于pivot的元素 //元素小于pivot //按降序排序 // if (array[j] >= pivot) if (array[j] <= pivot) { //第二个指针递增。 //将较小的元素替换为较大的元素 i++; int temp = array[i]; array[i] = array[j]; array[j] = temp; } } //所以左边的元素更小 //右边的元素大于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) { //选择轴位置并将所有元素放小 //左轴大于轴,右轴大于轴 int pi = partition(array, low, high); //对轴左侧的元素进行排序 quickSort(array, low, pi - 1); //对轴右侧的元素进行排序 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) {