【问题标题】:Java insertion sorting String ArrayJava插入排序字符串数组
【发布时间】: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] 在循环的每次迭代中引用相同的值。
  • 仅供参考,你让整个ccount 的东西更难阅读。为什么要计数c-1 然后使用count + 1count + 1 c;没有?
  • @SaschaKolberg 的建议解决了您的问题
  • @Ben 好吧,当我运行它时,它会打印出您期望的确切输出。因为您在第一次通过 while 循环时用新值覆盖了 sort[c]

标签: java arrays string sorting insertion-sort


【解决方案1】:

解决了!!!我所做的只是编辑了while 循环并在其下方注释了下一行。

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]))
        {
            String temp = sort[count+1];
            sort[count + 1] = sort[count];
            sort[count] = temp;
            count--;
        }
        //sort[count + 1] = sort[c]; This Line is in comment because it is not needed
    }
        //print out the array
        for(int n = 0; n < sort.length; n++)
            System.out.print(sort[n] + " ");

}

【讨论】:

    【解决方案2】:

    while 循环后这一行出现逻辑错误

     sort[count + 1] = sort[c];
    

    您正在使用 sort[c] ,其中数组由上述 while 循环操作,并且索引被打乱。相反,您应该使用 key 变量,用于存储要比较的当前值,因为它被循环覆盖。

     sort[count + 1] = key;
    

    这使代码完美运行。希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      相关资源
      最近更新 更多