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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With