// 示例代码:Java 中的快速排序算法
public class QuickSort {
// 快速排序的主方法
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
int pivotIndex = partition(array, low, high);
quickSort(array, low, pivotIndex - 1); // 对左子数组进行递归排序
quickSort(array, pivotIndex + 1, high); // 对右子数组进行递归排序
}
}
// 分区方法,返回枢轴位置
private static int partition(int[] array, int low, int high) {
int pivot = array[high]; // 选择最后一个元素作为枢轴
int i = low - 1; // i 是小于枢轴的最后一个元素的索引
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
i++;
swap(array, i, j); // 将小于等于枢轴的元素移到左边
}
}
swap(array, i + 1, high); // 将枢轴放到正确的位置
return i + 1;
}
// 交换数组中的两个元素
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// 测试快速排序算法
public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
System.out.println("原始数组: ");
printArray(array);
quickSort(array, 0, array.length - 1);
System.out.println("排序后的数组: ");
printArray(array);
}
// 打印数组的方法
private static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
}
quickSort 方法:这是快速排序的主方法,它递归地对数组进行排序。通过调用 partition 方法将数组分成两部分,并分别对这两部分进行排序。partition 方法:该方法用于选择一个枢轴(pivot),并将其放置在正确的位置,使得枢轴左边的所有元素都小于等于它,右边的所有元素都大于它。swap 方法:用于交换数组中的两个元素。main 方法:用于测试快速排序算法,打印排序前后的数组。希望这段代码和解释对你有帮助!
上一篇:java 数组初始化
下一篇:java 生成pdf
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站