Java_文字列のソート
package cn.myAlgorithm;
class StrSort {
public static void main(String[] args) {
String[] str = new String[6];
str[0] = "abduction";
str[1] = "boy";
str[2] = "applicant";
str[3] = "apple";
str[4] = "abduct";
str[5] = "abandon";
String temp;
// compare
for (int i = 0; i < str.length; i++) {
boolean flag = true;
for (int j = 0; j < str.length - i - 1; j++) {
if (!campare(str[j], str[j + 1])) {
temp = str[j];
str[j] = str[j + 1];
str[j + 1] = temp;
flag = false;
}
}
if (flag) {
break;
}
}
for (String string : str) {
System.out.println(string);
}
}
//
public static boolean campare(String str1, String str2) {
// , , true, false
boolean flag = true;
for (int i = 0; i < str1.length() && i < str2.length(); i++) {
// ,
if (str1.charAt(i) > str2.charAt(i)) {
flag = false;
break;
} else if (str1.charAt(i) < str2.charAt(i)) {
break;
} else {
// , , for
if (i != Math.min(str1.length() - 1, str2.length() - 1)) {
continue;
} else {
// ,
if (str1.length() <= str2.length()) {
break;
} else {
flag = false;
break;
}
}
}
}
return flag;
}
}
結果abandon abduct abduction apple applicant boy