请使用quick sort以数列 12 18 6 16 27 14 27 35 54 45 排序写出对应java代码
时间: 2023-12-28 13:03:33 浏览: 30
以下是使用快速排序算法对给定数列进行排序的Java代码:
```java
public class QuickSort {
public static void main(String[] args) {
int[] arr = {12, 18, 6, 16, 27, 14, 27, 35, 54, 45};
quickSort(arr, 0, arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int pivot = partition(arr, left, right);
quickSort(arr, left, pivot-1);
quickSort(arr, pivot+1, right);
}
}
public static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[right];
arr[right] = temp;
return i+1;
}
}
```
输出结果为:`[6, 12, 14, 16, 18, 27, 27, 35, 45, 54]`