题目:字符串排序
分析:
- 根据已经的字符串,先进行第一个字母排序,在进行第二个字母的排序
1 public class _040PrintString {
2
3 public static void main(String[] args) {
4 printString();
5 }
6
7 private static void printString() {
8 int N = 5;
9 String temp = null;
10 String[] string = new String[N];
11 string[0] = "matter";
12 string[1] = "state";
13 string[2] = "solid";
14 string[3] = "liquid";
15 string[4] = "gas";
16
17 for (int i = 0; i < N; i++) {
18 for (int j = i + 1; j < N; j++) {
19 if (compare(string[i], string[j]) == false) {
20 temp = string[i];
21 string[i] = string[j];
22 string[j] = temp;
23 }
24 }
25 }
26
27 for (int i = 0; i < N; i++) {
28 System.out.println(string[i]);
29 }
30 }
31
32 public static boolean compare(String s1, String s2) {
33 boolean result = true;
34
35 for (int i = 0; i < s1.length() && i < s2.length(); i++) {
36 if (s1.charAt(i) > s2.charAt(i)) {
37 result = false;
38 break;
39 } else if (s1.charAt(i) < s2.charAt(i)) {
40 result = true;
41 break;
42 } else {
43 if (s1.length() < s2.length()) {
44 result = true;
45 } else {
46 result = false;
47 }
48 }
49 }
50
51 return result;
52 }
53 }