Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two elements of an array function [closed]

Tags:

c

Can you help me by telling me what is wrong with this? Why is the swap function not working?

void swap(int a[], int b, int c) {
    int temp = a[b];
    a[b] = a[c];
    a[b] = temp;
}

void bubble1 (int a[], int N){
    int i;
    for(i=0;i<N-1;i++){
        if(a[i]>a[i+1]){
            swap(a,i,i+1);
        }
    }
}


void main() {
    int N = 11;
    int a[12]={5,3,12,4,25,10,14,35,2,8,13};

    bubble1 (a,N);

    int i;
    for(i = 0; i < N; i++){
        printf("%d\n",a[i]);
    }
}

If I don't use the swap function and do the swapping manually in the "bubble" function it works. However if I use the swap it doesn't work, even though it's exactly the same. What am I doing wrong here?

like image 653
Richard Avatar asked Mar 15 '23 18:03

Richard


1 Answers

 int temp = a[b];
 a[b] = a[c];
 a[b] = temp;

Simple typo, you are assigning to a[b] twice. The second one should be a[c]

like image 192
mtijanic Avatar answered Mar 28 '23 18:03

mtijanic