Java 中字符串無法直接使用 >、< 比較大小,需借助 compareTo 或自定義比較邏輯。本文演示基於字符 ASCII 碼值的字符串數組冒泡排序實現,並解析比較規則。
"abc" > "ab"。import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class StringSort {
private static final Log LOG = LogFactory.getLog(StringSort.class);
/**
* 對字符串數組進行升序排序(冒泡排序)
* @param keys 待排序數組
* @return 排序後數組(原地排序並返回)
*/
public static String[] sort(String[] keys) {
if (keys == null || keys.length <= 1) return keys;
for (int i = 0; i < keys.length - 1; i++) {
for (int j = 0; j < keys.length - i - 1; j++) {
if (isGreater(keys[j], keys[j + 1])) {
String temp = keys[j];
keys[j] = keys[j + 1];
keys[j + 1] = temp;
}
}
}
return keys;
}
/**
* 判斷 pre 是否大於 next
*/
private static boolean isGreater(String pre, String next) {
if (pre == null || next == null || pre.isEmpty() || next.isEmpty()) {
LOG.error("字符串比較參數不能為空!");
return false;
}
char[] cPre = pre.toCharArray();
char[] cNext = next.toCharArray();
int minLen = Math.min(cPre.length, cNext.length);
for (int i = 0; i < minLen; i++) {
if (cPre[i] > cNext[i]) return true;
if (cPre[i] < cNext[i]) return false;
}
// 前 minLen 字符相等,長度長者視為大
return cPre.length > cNext.length;
}
public static void main(String[] args) {
String[] keys = sort(new String[]{"fin", "abc", "shidema", "shide", "bushi"});
for (String key : keys) {
System.out.println(key);
}
}
}
abc bushi fin shide shidema
Arrays.sort(keys) 或 Arrays.sort(keys, String::compareTo),底層採用 TimSort(歸併+插入混合),性能遠優於冒泡排序 O(n²)。Comparator:Arrays.sort(keys, String.CASE_INSENSITIVE_ORDER)。