你能用JAVA写一个快速排序吗
是的,以下是使用JAVA编写的快速排序算法:
public class QuickSort {
public static void main(String[] args) {
int[] arr = {10, 7, 8, 9, 1, 5};
int n = arr.length;
QuickSort ob = new QuickSort();
ob.sort(arr, 0, n - 1);
System.out.println("排序后的数组:");
for (int i : arr) {
System.out.print(i + " ");
}
}
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);
}
}
int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = (low - 1); // 比 pivot 小的元素的指针
for (int j = low; j < high; j++) {
// 当前元素小于或等于 pivot
if (arr[j] <= pivot) {
i++;
// 交换 arr[i] 和 arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// 交换 arr[i + 1] 和 arr[high]
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
}
在快速排序算法中,partition()方法选择数组中的一个元素作为pivot(通常为最后一个元素),并将数组分成两个子数组:一个子数组的元素小于pivot,另一个子数组的元素大于pivot。sort()方法递归地调用partition()方法,并对两个子数组进行排序,最终得到排序后的数组。
原文地址: https://www.cveoy.top/t/topic/8Sx 著作权归作者所有。请勿转载和采集!