C++ help arrays

does anyone know how to write a function that organize an array like this:?
for example:
1
2
3
4
5
18 9   20 7  90
65 4   77 83 32
2  34  12 20 11
22 23  10 89 57
1  28  55  0 99


becomes:
1
2
3
4
5
0  1  4  10 20
2  7  11 20 32
9  12 22 34 65
18 23 55 77 89
28 57 83 90 99


it should be like this(if you didn't understand what i meant):
1
2
3
1 2 4
3 5 7
6 8 9


i started with this code but i think it's wrong:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void organizearray(int arr[N][N])
{
	int SwapHolder;
	for(int c=0 ; c<N ;c++)
	{
	for(int r=0 ; r<N ;r++)
		 { 
			 if(arr[c][r]>arr[c][r+1])
            {
			SwapHolder= arr[c][r+1];
			 arr[c][r+1]=arr[c][r];
			 arr[c][r]=SwapHolder;
			 }
		 }
	}
}
Last edited on
Why dont you use vectors? Or check the standard algorithm header here http://www.cplusplus.com/reference/algorithm/ they must have some sorting function.

Aceix.
Last edited on
hello aceix thanks for your reply but our teacher didn't teach us the algorithm header... he only taught us the bubble sort... :/
Its your assignment so its better to do it your self :P

Okay let me give you some hints ...
when you are getting new value from array ,, check what's wrong with it..
haha please help me i tried so hard!!
more hints?? :P
can you fix my code ?:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void organizearray(int arr[N][N])
{
	int SwapHolder;
	for(int c=0 ; c<N ;c++)
	{
	for(int r=0 ; r<N ;r++)
		 { 
			 if(arr[c][r]>arr[c][r+1])
            {
			SwapHolder= arr[c][r+1];
			 arr[c][r+1]=arr[c][r];
			 arr[c][r]=SwapHolder;
			 }
		 }
	}
}
If the rule is supposed to be smallest to largest, your example is flawed.
e.g. you have 2 and 7 in the second row. Shouldn't they be in the first row?

You have a couple of problems with your algorithim.

1) In lines 8,10 and 11, you refer to arr[c][r+1]. That's going to be a problem when is r equal to N-1. You're going to be referencing a row outside the array.

2) You're only making a single pass through the array. You're not going to catch multiple transpositions. Consider 3 2 1. You first compare and swap 3 and 2 resulting in 2 3 1. You then compare and swap 3 and 1, resulting in 2 1 3. You never go back to reconsider 2 and 1 which are still out of order.


Last edited on
not from smallest to largest sorry
i meant to sort them diagonally
do you have any idea how?
because i tried different type of methods none of them worked :/
Topic archived. No new replies allowed.