0

I am trying to implement INSERTION SORT here in C, which I think I've done successfully. However, I am having problems in passing arrays as arguments.

I want in place sorting, which means that the original array passed into the insertion_sort function should contain the elements in the sorted array itself.

#include<stdio.h>

int * insertion_sort(int *a,int length)
{
    int j;
    for(j=1;j<length;j++)
    {
        int i,key=a[j];
        for(i=j-1;j>=0;j--)
        {
            if(a[i]<=key)
                break;
            a[i+1]=a[i];
        }  
        a[i+1]=key;
    }

    return *a;
}

int main(void)
{
    int a[]={10,12,7,6,9,8};
    insertion_sort(a,6);
    int i;    
    for(i=0; i<6; i++)
       printf("%d\n", a[i]);

    return 0;
}

EDIT Nothing gets printed in the output screen. Help me find the bug here. Thanks !!

1
  • You're not "Passing pointers to an array" here. You're just passing pointers to an int Commented Mar 3, 2013 at 19:57

1 Answer 1

4

1.You probably meant to use i in the inner loop:

Change:

for(i=j-1;j>=0;j--) 
          ^^   ^^

to:

for(i=j-1;i>=0;i--)

2.You don't have to return anything as the original array gets modified (which is just as well since you ignore the returned value).

3.Array index starts from 0. Change outer loop to: for(j=0;j<length;j++)

Sign up to request clarification or add additional context in comments.

5 Comments

Ok.. Thanks.. What if I didn't pass the pointer as the argument. Rather I pass void insertion_sort(int a[],int length). Now If I print the array from the main method, will it print the sorted array or the initial array itself ?
insertion_sort(int a[],int length) is same as insertion_sort(int *a,int length). Remove the return statement once you change to void.. (it's wrong atm).
I removed the return statement.. But if I use insertion_sort(int a[],int length) isn't it call by value, where as insertion_sort(int *a,int length) is call by reference. Right ??
And in the outer loop, I can start picking up keys from the second element right, as a one element array is always sorted. So, is there a reason why I should do this for(j=0;j<length;j++)??
Arrays decay into a pointer when you pass to a function. So whether you write it as insertion_sort(int a[],int length) or insertion_sort(int *a,int length), compiler sees them as insertion_sort(int *a,int length)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.