public class ArrayTest03 {
public static void main(String[] args) {
String s= “dacqebf”;
// B:把字符串转换成字符数组
char[] chs= s.toCharArray();
//C:对字符数组进行排序
bubbleSort(chs);
printArray(chs);
selectSort(chs);
printArray(chs);
//D:把排序后的字符数组转成字符串
String result = String.valueOf(chs);
}
//遍历数组:
public static void printArray(char[] chs) {
System.out.print("[");
for(int x=0;x<chs.length;x++) {
if(x==chs.length-1) {
System.out.print(chs[x]);
} else {
System.out.print(chs[x]+", “);
}
}
System.out.println(”]");
}
//冒泡排序
public static void bubbleSort(char[] chs) {
for(int x=0;x<chs.length-1;x++) {
for(int y=0;y<chs.length-1-x;y++) {
if(chs[y]>chs[y+1]) {
char temp=chs[y];
chs[y]=chs[y+1];
chs[y+1]=temp;
}
}
}
}
//选择排序
public static void selectSort(char[] chs) {
for(int x=0;x<chs.length-1;x++) {
for(int y=1;y<chs.length-1;y++) {
if(chs[x]>chs[y]) {
char temp=chs[x];
chs[x]=chs[y];
chs[y]=temp;
}
}
}
}
}