简体   繁体   English

为什么我不想在插入类型中嵌入此循环?

[英]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.

相关问题 每当我在 java 中运行插入排序程序时,都会发生异常.. 但我不知道为什么 - Whenever I run the insertion sort program in java, exception occurs .. but i don't know why 我的KeyBindings不起作用,我想知道原因 - My KeyBindings don't work and I want to know why 我不知道为什么“while”循环阻塞了我的 onClickListener - I don't know why the "while" loop is blocking my onClickListener 计数器没有随着我的循环更新,我不知道为什么 - the counter is not updating with my loop and I don't know why 我不明白为什么我的嵌套 for 循环有效 - I don't understand why my nested for loop works 我不知道为什么我的数组没有在此冒泡排序中保存其随机值 - I don't know why my array doesn't have its random values saved in this bubble sort Java中带有辅助方法的插入排序不起作用。 有人看到我想念的吗? - Insertion-sort in java with helper method don't work. Anyone see what I'm missing? 我的 for 循环在 int 数组中添加了额外的元素,我不明白为什么 - extra element being added in my int array by my for loop, I don't understand why 为什么我们不能改变插入排序的 while 循环中语句的顺序? - Why can't we change the order of statements in insertion sort's while loop? Java-为什么气泡排序比插入排序快? - Java - Why is my Bubble Sort faster than my Insertion Sort?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM