Search code examples
insertion

Mistake with insertion sort realisation in C


Here is my code

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

The output is 13425. It's entering the while loop enough times to move the 2(the last element) to its place, but for some reason it isn't.


Solution

  • Try like this:

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

    }