gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:15:56 25 4
gpt4 key购买 nike

我不确定我的插入排序做错了什么。似乎对于 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 条件)。

您只是覆盖其中一个。

祝你好运。

关于java - 我的插入排序有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22472712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com