本案例采用快速排序,如果不懂可参考本人另一篇博客https://blog.csdn.net/qq_42192693/article/details/80938172
1,字符串排序,经常会用到
import java.util.Arrays;
public class 字符串排序 {
public static void main(String[] args) {
char[] str = { 's', 'd', 'a', 'w', 't', 'g', 'j', 'h', 'o' };
kuaiSu(str, 0, str.length - 1);
System.out.println(Arrays.toString(str));
}
static void kuaiSu(char a[], int left, int right) {
int f, l, r;
char t;
l = left;
r = right;
f = a[(left + right) / 2];
while (l < r) {
while (a[l] < f) {
++l;
}
while (a[r] > f) {
--r;
}
if (l <= r) {
t = a[l];
a[l] = a[r];
a[r] = t;
++l;
--r;
}
}
if (1 == r) {
l++;
}
if (left < r) {
kuaiSu(a, left, l - 1);
}
if (l < right) {
kuaiSu(a, r + 1, right);
}
}
}
2,字符串数组排序,根据字典顺序,按Unicode值进行排序
import java.util.Arrays;
public class 字符串数组排序 {
public static void main(String[] args) {
String arr[]={"One","World","Dream","Beijing","Olympic"};
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(String arr[], int left, int right) {
String f, t;
int rtemp, ltemp;
ltemp = left;
rtemp = right;
f = arr[(right + left) / 2];
while (ltemp < rtemp) {
while (arr[ltemp].compareTo(f) < 0) {
++ltemp;
}
while (arr[rtemp].compareTo(f) > 0) {
--rtemp;
}
if (ltemp <= rtemp) {
t = arr[ltemp];
arr[ltemp] = arr[rtemp];
arr[rtemp] = t;
--rtemp;
++ltemp;
}
}
if (left == rtemp) {
ltemp++;
}
if (left < rtemp) {
quickSort(arr, left, ltemp - 1);
}
if (ltemp < right) {
quickSort(arr, rtemp + 1, right);
}
}
}