[英]Why I don't want to embed this loop in my insertion sort?
I have a class and right now we are doing insertion sort. 我有一堂课,现在我们正在做插入排序。 I think my code worked properly but my professor said not to embed one of my loops (it shifts the values in my array over) and that it should be done while "searching". 我认为我的代码可以正常工作,但是教授说不要嵌入我的一个循环(它将数组中的值移过来),并且应该在“搜索”时完成。
public static void insertionSort(int array[]) {
int n = array.length;
for(int i = 0; i < n; i++) {
int nextIndex = i;
for(int j = 0; j < i; j++) {
if(array[nextIndex] < array[j]) {
int temp = array[nextIndex];
// ********************************
for(int k = i; k > j; k--) {
array[k]=array[k-1];
}
// ********************************
array[j]=temp;
j = i
}
}
}
}
What's wrong with the above? 上面有什么问题?
I think what your professor meant is this: You are currently looking through the sorted part of your array [0..i] from bottom to top to find the position at which the new element should be inserted. 我认为您的教授的意思是:您当前正在从下至上浏览数组[0..i]的排序部分,以查找应插入新元素的位置。 Afterwards you move through your array from top to bottom to shift the new element to the right position. 然后 ,从上到下遍历数组,以将新元素移到正确的位置。
Instead, you could just move the new element through the element and simultaneously look for the right position, similar to Bubblesort, if you know the algorithm. 相反,如果您知道算法,则可以将新元素移动通过该元素, 同时寻找正确的位置,类似于Bubblesort。 This saves you this for
-loop your prof marked. 这样可以节省你这for
-loop您教授标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.