在C中使用插入排序实现的错误

时间:2014-05-08 14:56:42

标签: insertion

这是我的代码

#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(最后一个元素)移动到它的位置,但由于某种原因它不是。

2 个答案:

答案 0 :(得分:0)

我发现了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;
}

答案 1 :(得分:0)

试试这样:

#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;

}