简体   繁体   中英

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;
}

*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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM