快速排序
- 编程实现快速排序函数。public static void quickSort(int arr[], int low, int high)。其中arr存放待排序的数据,数组长度不大于1000
- 函数接口定义:
/* 对长度为n的数组arr执行快速排序 */
public static void quickSort(int arr[], int low, int high);
请实现quickSort函数,使排序后的数据从小到大排列。
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int [n];
for(int i = 0; i < n; i ++) {
arr[i] = scanner.nextInt();
}
scanner.close();
quickSort(arr, 0, n - 1);
print(arr);
}
public static void print(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println("");
}
// ---------------------------------------------------------------------------
// 【实现代码如下】
// 排序函数
public static void quickSort(int arr[], int low, int high) {
// 如果当前子数组的低索引小于高索引,说明子数组至少有两个元素,可以进行排序
if (low < high) {
// 通过partition函数将数组分为两部分,并返回pivot(基准)元素的索引
int pivotIndex = partition(arr, low, high);
// 递归地对基准左边的子数组进行快速排序
quickSort(arr, low, pivotIndex - 1);
// 递归地对基准右边的子数组进行快速排序
quickSort(arr, pivotIndex + 1, high);
}
}
// 获取基准元素函数
private static int partition(int arr[], int low, int high) {
// 选择最后一个元素作为pivot(基准)
int pivot = arr[high];
// i指针用于跟踪比pivot小的元素应该放置的位置
int i = low - 1;
// 遍历除了pivot外的所有元素
for (int j = low; j < high; j++) {
// 如果当前元素小于pivot,则将其与i指针所指向位置的下一个元素交换
if (arr[j] < pivot) {
i++;
// 交换arr[i]和arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// 将pivot放置到正确的位置上(所有比它小的元素都在它左边,比它大的都在右边)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
// 返回pivot元素的新索引
return i + 1;
}
}