java插入排序递归

时间:2011-09-28 15:57:12

标签: java arrays recursion insertion

我有一个数组,必须使用插入排序对它们进行排序。我试图使用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);

        }
    } 

3 个答案:

答案 0 :(得分: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.
}

答案 1 :(得分:0)

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

答案 2 :(得分: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!!!!
相关问题