0

我有一个数组,必须使用插入排序对它们进行排序。我尝试使用 compareTo 方法遍历数组并查看更大的内容。我遇到了一个问题,因为我试图用一个明显不起作用的字符串引用数组索引(那是在 compareTo(a[key]) 处)。

任何有关如何执行此操作的建议或提示将不胜感激。

这就是我到目前为止所拥有的。这是一个好的开始吗?还是朝着正确的方向开始?

 public void insertionSort() 
    { 
        insertionSort(a.length-1);
    } 



    private void insertionSort(int n)
    {
        String temp; 
        if(n <= 1)
        {
        //Do nothing, easiest case
        }

        else
        {
        for(int i = 1; i < a.length; i++)
        {
        int j;
        String key = a[i];

            while((j >= 0) && (a[i].compareTo(a[key]) > 0))
            {
            a[i+1] = a[i];
            j--;
            }
            a[i+1] = key;
        }   

        insertionSort(n-1);

        }
    } 
4

3 回答 3

1

我的第一个建议是,如果传入所需的参数,通常更容易理解方法。根本不清楚是什么a;我希望公共insertionSort方法将要排序的对象作为参数。(我想如果您在自己的类似列表的类上定义它,它并没有那么糟糕,但听起来不像是这种用法)。

同样,我不完全确定n应该是什么(大概是您知道的索引超出了排序)但是您根本没有在私有方法的主体中使用它,所以您只是在做同样的n事情.

您似乎还交换了 的元素a,而在插入排序中您不需要这样做。这看起来更像是冒泡排序。

尝试首先将方法编写为伪代码(例如注释)来布置您的方法,然后用少量代码充实每个注释。这样做可以避免过于拘泥于细节,通常概念上的错误会显得更明显,也更容易避免。这可能看起来像:

public static int[] insertionSort(int[] input) {
    // Create the array to hold the results

    // Iterate through the contents of input and insert each one into
    // the result array in order (method call here)

    // return the result array
}

private void insertOneElement(int toInsert, int[] resultArray) {
    // Compare toInsert with first element of resultArray

    // etc.
}
于 2011-09-28T16:06:48.647 回答
0

只需将其更改为a[j].compareTo(key)(注意您要比较a[j],而不是a[i])。j正如 smas 评论的那样,您还需要初始化。

于 2011-09-28T16:04:38.367 回答
0

替换内循环如下:

j = i - 1;  //initialize j!!!
String key = a[i];   //take value
while((j >= 0) && (a[j].compareTo(key) > 0)){//Compare with key!!!
     a[j+1] = a[j];
     j--;
}
a[j + 1] = key; //index is j here!!!!
于 2011-09-28T16:09:43.557 回答