Ezerk February 2016

C- Insertion sort

What's wrong with this code? while loop part doesn't work. if statement is not enough to terminate while loop

int main(void) {

    int data[SIZE] = { 12,2,5,8,2,45,89,0,12,4 };

    int i, j, tmp;

    for (i = 0; i < SIZE-1; i++) {
        j = i + 1;
        tmp = data[j];
        while (j > 0){
            if(data[j-1] > tmp){
                data[j] = data[j - 1];
                j--;
            }
        }
        data[j] = tmp;
    }

    for (i = 0; i < SIZE; i++)
        printf("%d, ", data[i]);

return 0;
}

Answers


Rabbid76 February 2016

j--; is inside your if statement. If data[j-1] > tmp is false your loop will not terminate. Apart from this your algorithm does not sort the array. Adapt your code like this:

int main (void)
{
    int data[SIZE] = { 12,2,5,8,2,45,89,0,12,4 };

    int i, j, tmp;

    for (i = 0 ; i < SIZE - 1; i++)
    {
        j = i+1;
        while ( j > 0 && data[j] < data[j-1])
        {
            tmp       = data[j];
            data[j]   = data[j-1];
            data[j-1] = tmp;
            j--;
        }
    }

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

Post Status

Asked in February 2016
Viewed 2,588 times
Voted 7
Answered 1 times

Search




Leave an answer