# Thread: Help with a data sorting algorithm

1. ## Help with a data sorting algorithm

I've worked for two days on this algorithm but I'm stumped.
It's not printing out what the instructor states.
Where am I going wrong?

Mike

/*Arrange the following single dimension array in column major order. (Yes, the entire array, not just each column separately)

4 5 6
4 5 6
7 8 9
10 11 12
7 8 9

RULES: DO NOT use printf in some way to make it print in the correct order.
Instead, Move the items in the linear array to make this so.
if printed linearly it should print:
4,6,9,4,7,9,5,7,10,5,8,11,6,8,12.
*/
Code:
```#include<stdio.h>

int main(){

int array[15]={4,5,6,4,5,6,7,8,9,10,11,12,7,8,9};
int i,top,temp;
for(top=0; top<=14; top=top+1){
for(i=top+1; i<=14; i++){
if(array[top]>array[i]){
temp=array[top];
array[top]=array[i];
array[i]=temp;
break;
}
if(array[top]==array[i] && (top+1)<14 && (top!=i && (top+1)!=i)){
temp=array[top+1];
array[top+1]=array[i];
array[i]=temp;
break;
}
}
}

for(i=0; i<15; i++)
printf("%d,", array[i]);

return 1;
}```

2. How is this sorting? There is no logical order to the end result.

4,5,6
4,5,6
7,8,9
10,11,12
7,8,9

4,6,9
4,7,9
5,7,10
5,8,11
6,8,12

Gotcha. It helps if you display the output correctly. Sort "columns" of every third place. Thus, when you're looping through to sort, increment or decrement in steps of three.

Personally, I'd probably design a function that took the five arguments and returned a pointer to a static array of them. Then I'd overwrite their places in line with the contents of the array.
[/edit]

Quzah.

3. If the number-example of quzah is correct, then you could perform these steps:

1. Put all elements in a linear list.

Original array:

4,5,6
4,5,6
7,8,9
10,11,12
7,8,9

Gives list:

[4, 5, 6, 4, 5, 6, 7, 8, 9, 7, 8, 9, 10, 11, 12, 7, 8, 9]

2. Sort the linear list.

Sorting gives:

[4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 11, 12]

Indexed as:

[n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12]

3. Rearrange the list:

Output should be:

4,6,9
4,7,9
5,7,10
5,8,11
6,8,12

Which is:

n1 n5 n9
n2 n6 n10
n3 n7 n11
n4 n8 n12

Rearranging can be done easily. Put the first N characters in the linear list in the first colum, the second N characters in the second colum. Here N is the number of rows in the original matrix.