JAVA快速排序怎么写
时间: 2023-03-10 22:34:31 浏览: 115
Java快速排序的一个实现如下:
public class QuickSort {
public static void sort(int[] arr, int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1) {
sort(arr, left, index - 1);
}
if (index < right) {
sort(arr, index, right);
}
}
public static int partition(int[] arr, int left, int right) {
int pivot = arr[(left + right) / 2];
while (left <= right) {
while (arr[left] < pivot) left++;
while (arr[right] > pivot) right--;
if (left <= right) {
swap(arr, left, right);
left++;
right--;
}
}
return left;
}
public static void swap(int[] arr, int left, int right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}
阅读全文