繁体   English   中英

我的插入排序有什么问题?

[英]Whats wrong with my insertion sort?

我不确定我的插入排序有什么问题。 似乎对于i的每个增量,都会将array [i]复制到array [i + 1],依此类推,直到整个数组被原始对象array [i]填充为止。

public static void insertionSort(Course[] courseArray, String sortBy) {
    Course value;   // the next value from the unsorted list to be inserted into the sorted list
    int i;     // i is a pointer to an item in the unsorted list
    int j;    // j is a pointer to an item in the sorted list; originally the sorted list is just a[0]

    for (i = 1; i < courseArray.length - 1; i++) 
    {

        value = courseArray[i];

        j = i - 1;

        while (j >= 0 && (courseArray[j].compareByCourse(value)) < 0) {
            courseArray[j + 1] = courseArray[j];

            j = j - 1;

        }
        courseArray[i + 1] = value;

        System.out.println("i= " + i + "--------------------------------------");

        for (int p = 0; p < courseArray.length; p++) 
        {
            System.out.println(courseArray[p].toString());
        }

    }//end for

}//end insertionSort()`

我看过许多插入排序示例,觉得好像写得正确,但是显然我错了。

您必须交换(交换)内部循环中的值(使用if条件)。

您只是覆盖其中之一。

祝好运。

暂无
暂无

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

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