Search code examples
carrayssortinginsertion

Sorting an array with Insertion Sort


My task is to write a function naive_sort() that takes an array of random generated integers as a parameter and sorts them. I need to use Insertion Sort. I have come to a point where i have no idea how to fix the problem, when i run the program nothing happens. Console stays empty.I'm fairly new to C programming so don't be surprised if you find a stupid mistake somewhere. Any help would be greatly appreciated.

EDIT: It's outputting a list of numbers but they are not being sorted, output example:

558915997481717626
152655717476818999

This is my code(EDITED):

    #include <stdio.h>
#include<conio.h>
#include <stdlib.h>
#include <time.h>

//Insertion Sort function to Sort Integer array list
int *naive_sort(int array[],int n)
{
    int j,temp,i;

    //Iterate start from second element
    for (i = 1; i < n; i++)
    {
        j = i;
        //Iterate and compare till it satisfies condition
        while ( j > 0 && array[j] < array[j-1])
        {
            //Swapping operation
            temp = array[j];
            array[j]   = array[j-1];
            array[j-1] = temp;
            j--;
        }
    }
    //return Sorted array
    return array;
}

int main()
{
    //declaring variables
    int array[10],i;
    int n = 10;

    srand (time(NULL)); //initialize random seed
    for (i=0; i<n; i++)
    {
            array[i] = rand() % 100;
            scanf("%d",&array[i]);
    }
    for(i=0; i<n; i++)
    {
        printf("%d", array[i]);
    }
    printf("\n");


    //calling naive_sort function defined above and getting
    //sorted array in sortArray variable
    naive_sort(array,n);

    //print sorted array
    for(i = 0; i<n; i++ )
    {
        printf("%d",array[i]);
    }
    printf("\n");
    return 0;
}

Solution

  • You didn' t initialze your local variable n, there is a return statment in the middle of your code, you access your array out of bounds in the first for loop (because of <=100). Adapt your code like this:

    #include <stdio.h>      // printf, scanf
    #include <stdlib.h>     // srand, rand
    #include <time.h>       // time 
    
    int main()
    {
        int array[100], i;
        int n = 100; // init n
    
        srand (time(NULL)); // initialize random seed
        for( i=0; i<n; i++ )
        {
            array[i] = rand() % 100; // replace this by scanf to read values from input
            // scanf("%d",&array[i]); 
        }
        for( i=0; i<n; i++ )
        {
            printf("%4d",array[i]);
        }
        printf( "\n" );
    
        naive_sort(array,n); // sort array
    
        for( i=0; i<n; i++ )
        {
            printf("%4d", array[i]);
        }
        printf( "\n" );
        return 0;
    }
    

    Your function naive_sort works as expected.