写一个java快速程序
以下是一个Java快速排序程序的示例:
public class QuickSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 3, 9, 1 };
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int pivot = partition(arr, left, right);
quickSort(arr, left, pivot - 1);
quickSort(arr, pivot + 1, right);
}
}
public static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; 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[right];
arr[right] = temp;
return i + 1;
}
}
这个程序使用快速排序算法对一个整数数组进行排序。快速排序是一种高效的排序算法,它的时间复杂度为 O(nlogn)。在这个程序中,我们使用递归的方式实现了快速排序。具体来说,我们首先选择一个轴值(pivot),然后将数组中的元素分为两部分,一部分小于轴值,一部分大于轴值。然后递归地对这两部分进行排序,直到整个数组有序。
原文地址: https://www.cveoy.top/t/topic/b7cU 著作权归作者所有。请勿转载和采集!