简体   繁体   English

Java插入排序字符串数组

[英]Java insertion sorting String Array

I'm trying to sort an array of strings alphabetically through comparing their first letters. 我正在尝试通过比较字符串的首字母来对字符串数组进行排序。 I can get an insertion sort working with integers but when I change the integers to strings and reference the integer values of the first character for comparison purposes it stops working. 我可以使用整数进行插入排序,但是当我将整数更改为字符串并引用第一个字符的整数值以进行比较时,它将停止工作。 Here is my code, could someone help me learn what I have done wrong? 这是我的代码,有人可以帮助我了解我做错了什么吗?

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] + " ");

}

This should output "ai bw ca dd ff gl " but instead it prints "ai gl gl gl ff gl " 这应该输出“ ai bw ca dd ff gl”,但输出“ ai gl gl gl ff gl”

Solved!!! 解决了!!! All I did was edited the while loop and commented the next line below it. 我所做的所有工作都在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] + " ");

}

After while loop there is logical error in this line 在while循环之后,此行中存在逻辑错误

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

you are using sort[c] where array is being manipulated by the above while loop and indexes are shuffled. 您正在使用sort [c],其中数组是由上述方法操纵的,而循环和索引是随机的。 Instead you should use the key variable, you used to store current value to be compared as that is over written by loop. 相反,您应该使用key变量,该变量用于存储要比较的当前值,因为当前值被循环覆盖。

 sort[count + 1] = key;

This makes the code work perfect. 这使代码工作完美。 Hope this helps 希望这可以帮助

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

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