Home > front end >  swap adjacent element in array using recursion
swap adjacent element in array using recursion

Time:10-02

I wrote a program to swap adjacent element of array using recursion:

static arr_len;

void swap(int *a, int len)
{
        int tmp;

        if(len == 0 )
                return;
        else {
                swap(a, len-1);

                if(len == arr_len-1)
                        return;
                else if (len > 1)
                        len  ;

                tmp = a[len];
                a[len] = a[len-1];
                a[len-1] = tmp;
        }
}

int main()
{
        int a[] = {1,2,3,4}, i;
        arr_len = sizeof(a)/sizeof(a[0]);

        swap(a, sizeof(a)/sizeof(a[0]));


        for (i = 0; i< 4; i  )
                printf("%d\n", a[i]);
}

This seems to work as I see output:

2

1

4

3

But soon I put more element in array as:

int a[] = {1,2,3,4,5,6}

I see this output:

2
1
4
5
6
3
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)

CodePudding user response:

For starters using the global variable arr_len is a bad idea.

In any case your function is invalid. Consider a simplified example when the array contains only 1 or 2 elements. When the array contains one element then you are accessing memory beyond the array using an invalid index equal to len in this statement

tmp = a[len];

The function can look much simpler. For example

void swap( int *a, size_t n )
{
    if ( !( n < 2 ) )
    {
        int tmp = a[0];
        a[0] = a[1];
        a[1] = tmp;
        swap( a   2, n - 2 );
    }
}    
  • Related