سؤال

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.

هل كانت مفيدة؟

المحلول

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;

}

نصائح أخرى

I found 3 mistakes

#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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top