写一个根据字符串排序的java代码
时间: 2024-05-03 11:20:50 浏览: 51
这是一个基于快速排序算法的示例代码,可以按照字符串字典序进行排序:
```
public class StringSorter {
public static void main(String[] args) {
String[] strings = {"apple", "banana", "cat", "dog", "egg", "frog"};
quickSort(strings, 0, strings.length - 1);
for (String s : strings) {
System.out.print(s + ", ");
}
}
public static void quickSort(String[] strings, int left, int right) {
if (left >= right) {
return;
}
int i = left;
int j = right;
String pivot = strings[left + (right - left) / 2];
while (i <= j) {
while (strings[i].compareTo(pivot) < 0) {
i++;
}
while (strings[j].compareTo(pivot) > 0) {
j--;
}
if (i <= j) {
String temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
i++;
j--;
}
}
quickSort(strings, left, j);
quickSort(strings, i, right);
}
}
```
阅读全文