Thread: bubble sorting a 2-d array

1. bubble sorting a 2-d array

I am having problems with bubble sorting a 2d array. I know I need 3 loops but I do not know where to put the third. any help would be greatly appreciated.

Code:
```void bubble(int arr[])
{
int i, j;

for (i = 0; i < SIZE - 1; i++)
{
for (j = SIZE - 1; j > i; j--)
if (arr[j - 1] > arr[j])
swap(&arr[j - 1], &arr[j]);
printf("\nAfter pass %d: ", i);
printArr(arr);
}
}

void swap(int *pNum1, int *pNum2)
{
int temp;   // NOT int *
temp = *pNum1;
*pNum1 = *pNum2;
*pNum2 = temp;
}```

2. u dont need three loops, its just the 2 loop, with 2 two two an check the elements and swap it, look at the following code which could help you

Code:
```/*program to arrange the array elements in increasing order*/
#include<stdio.h>

void swap(int*, int *);  // fucntion to sawp the elements

int main()
{
int a[10];
int i,j;

for(i=0;i<10;i++)
scanf("%d",&a[i]);

for(i=0;i<10-1;i++)
{
for(j=i+1;j<10;j++)
{
if(a[i]>a[j]) // check two elements of the array is i > j swap it
swap(&a[i],&a[j]);
}
}

for(i=0;i<10;i++)
printf("%d\t",a[i]);

getchar();
}

void swap(int *num1, int *num2)  // fucntion to swap the elements
{
*num1^=*num2;
*num2^=*num1;
*num1^=*num2;
}```
s.s.harish

3. Code:
```void swap(int *num1, int *num2)  // fucntion to swap the elements
{
*num1^=*num2;
*num2^=*num1;
*num1^=*num2;
}```
Don't do this. It's a stupid way to swap. Just use a temporary variable. Search the forums if you want to know why it's wrong to do.

Quzah.

4. Originally Posted by quzah
Don't do this. It's a stupid way to swap. Just use a temporary variable. Search the forums if you want to know why it's wrong to do.

Quzah.
Or I can just tell you, because this is one of those screwups that I never get tired of pointing out. Try the following main with your swap code. Then rewrite your swap with a temp variable and see which one really works.
Code:
```int main(void)
{
int a = 10;
int* b = &a;
printf("Before swap: a:%d b:%d\n",a,*b);
swap(&a,b);
printf("After swap: a:%d b:%d\n",a,*b);
return 0;
}```

5. fine i get the result as 0 for both a and b

is that b'cose it don't work for msomehting like this

swap(&a, &a);

when i do this it wont work as expected.
is that my thinking is correct, if not so please correct me

thank u very much

6. Originally Posted by stodd04
I am having problems with bubble sorting a 2d array. I know I need 3 loops but I do not know where to put the third. any help would be greatly appreciated.
Could you elaborate on your expected input and output?
Code:
```   int array[][3] =
{
{6,5,4},
{7,9,8},
{2,1,3},
};```
Would you expect this to be sorted into this?
Code:
```   {
{1,2,3},
{4,5,6},
{7,8,9},
}```
How are you evaluating less than, greater than, and equal to for each "row"? And do you intend to also sort within each "row"?

Or is the "2D array" really an array of strings?