【发布时间】:2015-08-29 17:38:40
【问题描述】:
我正在尝试通过比较字符串的第一个字母来按字母顺序对字符串数组进行排序。我可以使用整数进行插入排序,但是当我将整数更改为字符串并引用第一个字符的整数值进行比较时,它会停止工作。这是我的代码,有人可以帮助我了解我做错了什么吗?
public static boolean cSL(String a, String b)
{
int aN = (int)(a.charAt(0));
int bN = (int)(b.charAt(0));
if(aN < 97) aN += 32;//make case insensitive
if(bN < 97) bN += 32;
return(aN < bN);
}
public static void main(String[] args)
{
String[] sort = {"ai", "ff", "gl", "bw", "dd", "ca"};
for( int c = 1; c < sort.length; c++ )
{
String key = sort[c];
int count = c - 1;
while (count >= 0 && cSL(key, sort[count]))
{
sort[count + 1] = sort[count];
count--;
}
sort[count + 1] = sort[c];
}
//print out the array
for(int n = 0; n < sort.length; n++)
System.out.print(sort[n] + " ");
}
这应该输出“ai bw ca dd ff gl”,但它会打印“ai gl gl gl ff gl”
【问题讨论】:
-
您可能需要将
sort[count + 1] = sort[c];替换为sort[count + 1] = key; -
没看到。我认为除了使代码看起来更好之外,它不会改变任何东西,因为 key 和 sort[c] 在循环的每次迭代中引用相同的值。
-
仅供参考,你让整个
c和count的东西更难阅读。为什么要计数c-1然后使用count + 1?count + 1是c;没有? -
@SaschaKolberg 的建议解决了您的问题
-
@Ben 好吧,当我运行它时,它会打印出您期望的确切输出。因为您在第一次通过 while 循环时用新值覆盖了
sort[c]。
标签: java arrays string sorting insertion-sort