public class QuickSortClass {
public static void main(String[] args) throws Exception {
int[] nums = {2,7,8,9,3,1,4,6,5};
System.out.println(Arrays.toString(sort(nums)));
}
public static int[] sort(int[] sourceArray) throws Exception {
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
return quickSort(arr, 0, arr.length - 1);
}
private static int[] quickSort(int[] arr, int left, int right) {
if (left < right) {
int partitionIndex = partition(arr, left, right);
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
}
private static int partition(int[] arr, int left, int right) {
// 设定基准值(pivot)
int index = left + 1;
for (int i = index; i <= right; i++) {
if (arr[i] < arr[left]) {
swap(arr, i, index);
index++;
}
}
swap(arr, left, index - 1);
return index - 1;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}