Search code examples
c++argument-passinginsertion-sort

what is wrong in passing argument in function using reference


I'm trying to implement insertion sort. The algorithm works fine when I write swap method inside the while loop. But when I try to call swap() function, it gives wrong answer. Specifically, when I pass the parameter 'j', it is making the answer go wrong. Will you please tell me where I am making the mistake.(on ideone ![http://ideone.com/MoqHgn])

#include <iostream>
using namespace std;

void swap(int *x, int *y, int *j) { 
    int temp = *x;
    *x = *y;
    *y = temp;
    *j--;
}

int main() {
    int N;
    scanf("%d", &N);
    int a[N];
    for(int i = 0; i < N; i++) {
        scanf("%d", &a[i]);
    }
    for(int i = 1; i < N; i++) {
        int j = i;
        while(j > 0 && a[j-1] > a[j]) {
            swap(&a[j-1], &a[j], &j);
            //int temp = a[j];
            //a[j] = a[j-1];
            //a[j-1] = temp;
            //j--;  
        }
    }

    for(int i = 0; i<N; i++) {
        cout << a[i] << " ";
    }

    return 0;
}

Solution

  • *j-- is the same as *(j--), but you want (*j)--.

    Since you're coding in C++, why not pass by reference instead of using pointers?