what's wrong in this code for insertion sort?

65 Views Asked by At

i created one insertion sort code using nested for. just because I'm writing condition in if part separately inside for loop, it gives me different answers. please tell me what's wrong with my approach.

i tried searching online but i did not get the result this is my code:

#include <stdio.h>

int main() {
    int i, j;
    int arr[] = {32, 5, 45, 8, 17, 82, 10};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    printf("Before Sorting: ");
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    
    for (i = 1; i < size; i++) {
        int key = arr[i];
        for (j = i - 1; j >= 0; j--) 
        {
            if(arr[j] > key)
                arr[j + 1] = arr[j];
        }
        arr[j + 1] = key;
    }
    
    printf("\nAfter Sorting: ");
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}
1

There are 1 best solutions below

0
Vlad from Moscow On

The problem with the nested for loops

for (i = 1; i < size; i++) {
    int key = arr[i];
    for (j = i - 1; j >= 0; j--) 
    {
        if(arr[j] > key)
            arr[j + 1] = arr[j];
    }
    arr[j + 1] = key;
}

is that arr[0] is always set to key because after the inner for loop j is equal to -1.

You could rewrite them for example like

for (i = 1; i < size; i++) {
    int key = arr[i];
    j = i - 1;

    for ( ; j >= 0 && key < arr[j]; --j )
    {
        arr[j+1] = arr[j];
    }    

    arr[j+1] = key;
}

Pay attention to that the type of the value produced by the operator sizeof has type size_t. So it will be more correctly to write

size_t size = sizeof(arr) / sizeof(arr[0]);

Also you should declare variables in minimum scopes where they are used.

I would write the program the following way

#include <stdio.h>

int main( void )
{
    int arr[] = { 32, 5, 45, 8, 17, 82, 10 };
    size_t size = sizeof( arr ) / sizeof( arr[0] );

    printf( "Before Sorting: " );
    for ( size_t i = 0; i < size; i++)
    {
        printf( "%d ", arr[i] );
    }
    putchar( '\n' );

    for ( size_t i = 1; i < size; i++ )
    {
        if (arr[i] < arr[i - 1])
        {
            int key = arr[i];

            size_t j = i;

            for ( ; j != 0 && key < arr[j-1]; --j )
            {
                arr[j] = arr[j -1];
            }

            arr[j] = key;
        }
    }

    printf( "\nAfter Sorting: " );
    for ( size_t i = 0; i < size; i++)
    {
        printf( "%d ", arr[i] );
    }
    putchar( '\n' );
}