编写一个java字符串倒序排序的demo,时间复杂度为 O(nlogn)
时间: 2024-03-16 20:41:36 浏览: 78
下面是使用快速排序算法对字符串数组进行倒序排序的 Java 代码示例:
```java
import java.util.Arrays;
public class StringSort {
public static void main(String[] args) {
String[] arr = {"apple", "banana", "orange", "grape", "pear"};
// 快速排序
quickSort(arr, 0, arr.length - 1);
// 输出排序结果
System.out.println(Arrays.toString(arr));
}
public static void quickSort(String[] 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(String[] arr, int left, int right) {
String pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j].compareTo(pivot) > 0) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, right);
return i + 1;
}
public static void swap(String[] arr, int i, int j) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
```
输出结果为:
```
[pear, orange, grape, banana, apple]
```
阅读全文