用java写一个快速排序程序
时间: 2023-03-11 13:16:26 浏览: 35
java 排序 算法
我可以为你提供一段Java代码,用来实现快速排序:
public class QuickSort {
public static void main(String[] args) {
int[] array = {23, 11, 7, 29, 33, 59, 8, 20, 9, 3, 2, 6, 10, 44, 83, 28};
QuickSort qs = new QuickSort();
qs.qSort(array, 0, array.length - 1);
System.out.println("After sorting:");
for (int item : array) {
System.out.println(item + " ");
}
}
public void qSort(int[] array, int low, int high) {
if (low < high) {
int pivot = partition(array, low, high);
qSort(array, low, pivot - 1);
qSort(array, pivot + 1, high);
}
}
public int partition(int[] array, int low, int high) {
int pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (array[j] < pivot) {
i++;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1;
}
}
阅读全文