繁体   English   中英

Java插入排序字符串数组

[英]Java insertion sorting String Array

我正在尝试通过比较字符串的首字母来对字符串数组进行排序。 我可以使用整数进行插入排序,但是当我将整数更改为字符串并引用第一个字符的整数值以进行比较时,它将停止工作。 这是我的代码,有人可以帮助我了解我做错了什么吗?

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”

解决了!!! 我所做的所有工作都在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] + " ");

}

在while循环之后,此行中存在逻辑错误

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

您正在使用sort [c],其中数组是由上述方法操纵的,而循环和索引是随机的。 相反,您应该使用key变量,该变量用于存储要比较的当前值,因为当前值被循环覆盖。

 sort[count + 1] = key;

这使代码工作完美。 希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM