主要用了两个排序方法,冒泡排序和选择排序。
示例代码:
package cn.lgt.sortarray;
public class ZifuSort {
public static void main(String[] args) {
String str1 = "gdeacbf";
char[] chs1 = str1.toCharArray();
// 排序方法
//冒泡排序
maoPaoSort(chs1);
String result = String.valueOf(chs1);
System.out.println("result = " + result);
//选择排序
String str2 = "hmgdeacbf";
char[] chs2 = str2.toCharArray();
xuanZeSort(chs2);
String result2 = String.valueOf(chs2);
System.out.println("result2 = " + result2);
}
// 冒泡排序方法
public static void maoPaoSort(char[] chs) {
for (int i = 0; i < chs.length - 1; i++) {
for (int j = 0; j < chs.length - 1 - i; j++) {
if (chs[j] > chs[j + 1]) {
char temp = chs[j];
chs[j] = chs[j + 1];
chs[j + 1] = temp;
}
}
//String str1 = String.valueOf(chs);
//System.out.println(str1);
}
}
//选择排序算法
public static void xuanZeSort(char[] chs){
for(int i = 0; i < chs.length-1; i++){
for(int j = i+1; j<chs.length; j++){
if(chs[j] < chs[i]){
char temp = chs[j];
chs[j] = chs[i];
chs[i] = temp;
}
}
}
}
}