1. 程式人生 > >Java經典編程題50道之四十

Java經典編程題50道之四十

println static 英文字母 mat () else for ole math

將幾個字符串排序(按英文字母的順序)。

public class Example40 {
public static void main(String[] args) {
String[] s={"math","english","java","java web","rose"};
stringSort(s);
}

public static void stringSort(String[] s) {
String temp = null;

for (int i = 0; i < s.length; i++) {

for (int j = i + 1; j < s.length; j++) {
if (compare(s[i], s[j])) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
}
public static boolean compare(String s1, String s2) {
boolean result = true;
for (int i = 0; i < s1.length() && i < s2.length(); i++) {
if (s1.charAt(i) > s2.charAt(i)) {
result = false;
break;
} else if (s1.charAt(i) < s2.charAt(i)) {
result = true;
break;
} else {
if (s1.length() < s2.length()) {
result = true;
} else {
result = false;
}
}
}
return result;
}
}

Java經典編程題50道之四十