forked from shijiebei2009/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStringSort.java
More file actions
81 lines (75 loc) · 2.17 KB
/
Copy pathStringSort.java
File metadata and controls
81 lines (75 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package cn.codepub.algorithms.strings;
import java.util.Arrays;
/**
* <p>
* Created with IntelliJ IDEA. 2015/12/1 14:18
* </p>
* <p>
* ClassName:StringSort
* </p>
* <p>
* Description:实现一个简单的字符串按照字典序排序,不区分大小写
* </P>
*
* @author Wang Xu
* @version V1.0.0
* @since V1.0.0
*/
public class StringSort {
public static void main(String[] args) {
String[] strs = new String[]{"alphabet", "alligator", "alternate", "alternative"};
bubbleSort(strs);
System.out.println(Arrays.toString(strs));
}
/**
* 实现排序函数的主体
*
* @param strs 需要排序的字符串数组
*/
public static void bubbleSort(String[] strs) {
for (int i = 0; i < strs.length; i++) {
for (int j = strs.length - 1; j > i; j--) {
int compare = compare(strs[i], strs[j]);
if (compare > 0) {
//说明前面一个大
String temp = strs[i];
strs[i] = strs[j];
strs[j] = temp;
}
}
}
}
/**
* 辅助排序函数
*
* @param s1
* @param s2
* @return 1 前者大;-1 后者大;0 两者相等
*/
private static int compare(String s1, String s2) {
s1 = s1.toLowerCase();//全转小写
s2 = s2.toLowerCase();
int len1 = s1.length();
int len2 = s2.length();
int count = len1 < len2 ? len1 : len2;
for (int i = 0; i < count; i++) {
int first = (int) s1.charAt(i);//将字母强转为ASCII码
int second = (int) s2.charAt(i);
if (first < second) {
return -1;//前一个小
} else if (first > second) {
return 1;//后一个小
} else {
continue;
}
}
//如果全部比较完了,则谁短谁小
if (len1 < len2) {
return -1;
} else if (len1 > len2) {
return 1;
} else {
return 0;
}
}
}