Java插入排序字符串数组

时间:2015-08-29 17:38:40

标签: java arrays string sorting insertion-sort

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

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”

2 个答案:

答案 0 :(得分:0)

解决!!!我所做的只是编辑了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] + " ");

}

答案 1 :(得分:0)

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

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

你正在使用sort [c],其中数组被上面的while循环操作,并且索引被洗牌。相反,您应该使用键变量,用于存储要比较的当前值,因为它是由循环写的。

 sort[count + 1] = key;

这使代码完美无缺。希望这有帮助