快速排序算法java实现代码
时间: 2023-03-15 21:29:01 浏览: 159
快速排序算法的Java实现代码如下:
public class QuickSort {
public static void quickSort(int[] array, int start, int end) {
if (array.length < 1 || start < 0 || end >= array.length || start > end) return;
int smallIndex = partition(array, start, end);
if (smallIndex > start)
quickSort(array, start, smallIndex - 1);
if (smallIndex < end)
quickSort(array, smallIndex + 1, end);
}
public static int partition(int[] array, int start, int end) {
int pivot = (int) (start + Math.random() * (end - start + 1));
int smallIndex = start - 1;
swap(array, pivot, end);
for (int i = start; i <= end; i++)
if (array[i] <= array[end]) {
smallIndex++;
if (i > smallIndex)
swap(array, i, smallIndex);
}
return smallIndex;
}
public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
阅读全文