【问题标题】:Mistake with insertion sort realisation in CC中插入排序实现的错误
【发布时间】:2014-05-08 14:56:42
【问题描述】:

这是我的代码

#include <stdio.h>

int main(void){

    int unsorted[] = {1,3,4,5,2};
    int i = 0;
    int j = 0;
    int temp = 0;
    for(i = 1; i <= 5; i++){
        temp = unsorted[i];
        j = i - 1;
        while(unsorted[j] > unsorted[i]){
                unsorted[i] = unsorted[j];
                unsorted[j] = temp;
            }

}
        for(i = 0; i < 5; i++){
        printf("%i", unsorted[i]);
    }
    return 0;
}

输出是 13425。它进入 while 循环的次数足以将 2(最后一个元素)移动到它的位置,但由于某种原因它不是。

【问题讨论】:

  • for(i = 1; i &lt;= 5; i++){ temp = unsorted[i]; 可能和你当前的问题无关,但是考虑一下i 的值达到5时会发生什么。
  • 我没有想到这一点,我添加了一个 if 条件,所以如果 i

标签: insertion


【解决方案1】:

试试这样:

#include <stdio.h>
int main(void){

    int unsorted[] = {1,3,4,5,2};
    int i = 0;
    int j = 0;
    int temp = 0;
    for(i = 1; i < 5; i++){
        j = i;
        while(j>0 && unsorted[j]<unsorted[j-1]){
                temp = unsorted[j];
                unsorted[j] = unsorted[j-1];
                unsorted[j-1] = temp;
                j--;
            }

}
    for(i = 0; i < 5; i++){
    printf("%d", unsorted[i]);
}
return 0;

}

【讨论】:

    【解决方案2】:

    我发现了 3 个错误

    #include <stdio.h>
    
    int main(void){
    
        int unsorted[] = {1,3,4,5,2};
        int i = 0;
        int j = 0;
        int temp = 0;
        for(i = 1; i <= 5; i++){
            temp = unsorted[i]; // You are out of array boundaries here
            j = i - 1;
            while(unsorted[j] > unsorted[i]){
                // you need to place j-th element in (j+1)-th
                // position, but not in i-th position
                unsorted[i] = unsorted[j];
                unsorted[j] = temp; // you can do this one time after end of this cycle
                // You need to decrement j in this cycle until j >= 0
            }
    
        }
        for(i = 0; i < 5; i++){
            printf("%i", unsorted[i]);
        }
        return 0;
    }
    

    【讨论】:

    • 你需要将第 j 个元素放在第 (j+1) 个位置,而不是放在第 i 个位置 / 我不明白那些 j + 1 == i / 为什么我如果 unsorted[j] 就地,应该在 cicle 结束后用 temp 更改 unsorted[j]?
    • j + 1 == i 仅在 while 循环的第一次迭代中为真。第一次迭代后 j 减小。
    • 您应该在循环中执行此操作 unsorted[j+1] = unsorted[j];但未排序[j] = temp;你只能做一次
    猜你喜欢
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多