簡體   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