用java写一个快速排序的程序
时间: 2023-05-13 15:07:39 浏览: 41
下面是一个用Java实现快速排序的示例代码:
public class QuickSort {
public static void quickSort(int[] arr, int start, int end) {
if (start < end) {
int partitionIndex = partition(arr, start, end);
quickSort(arr, start, partitionIndex-1);
quickSort(arr, partitionIndex+1, end);
}
}
private static int partition(int[] arr, int start, int end) {
int pivot = arr[end];
int i = start-1;
for (int j=start; j<end; 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[end];
arr[end] = temp;
return i+1;
}
public static void main(String[] args) {
int[] arr = {3,5,7,2,1,4,6,8};
quickSort(arr, 0, arr.length-1);
for (int i : arr) {
System.out.print(i + " ");
}
}
}