sortArray(int[] arr,String sort)函数
时间: 2023-05-27 19:05:02 浏览: 85
该函数的作用是对一个整数数组进行排序,其中sort参数指定了排序方式,可以是"asc"表示升序排列,也可以是"desc"表示降序排列。
函数的签名如下:
public static int[] sortArray(int[] arr, String sort)
函数的参数说明:
- arr:待排序的整数数组
- sort:排序方式,可以是"asc"表示升序排列,也可以是"desc"表示降序排列。
函数的返回值是排序后的整数数组。
函数的实现思路:
根据sort参数的值,选择不同的排序方式,例如如果是"asc",则使用快速排序算法对数组进行升序排列,如果是"desc",则先对数组进行升序排列,然后再将数组反转得到降序排列。
函数的具体实现:(使用快速排序算法)
public static int[] sortArray(int[] arr, String sort) {
int len = arr.length;
if (len < 2) {
return arr;
}
if (sort.equals("asc")) {
quickSort(arr, 0, len - 1);
} else if (sort.equals("desc")) {
quickSort(arr, 0, len - 1);
reverseArray(arr);
}
return arr;
}
private static void quickSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int pivot = arr[(left + right) / 2];
int i = left;
int j = right;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
swap(arr, i, j);
i++;
j--;
}
}
quickSort(arr, left, j);
quickSort(arr, i, right);
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static void reverseArray(int[] arr) {
int len = arr.length;
for (int i = 0; i < len / 2; i++) {
int temp = arr[i];
arr[i] = arr[len - i - 1];
arr[len - i - 1] = temp;
}
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)