PDA

View Full Version : array 5*5

sabsa
12-15-2011, 02:47 PM
I am new in c++. I want to write a program getting array 5*5 and then sort it horizontally.could you please help me? I do not know what should I do exactly!
Thank you.

Apothem
12-16-2011, 07:11 AM
Well, you probably know this:
array[r][c]

Correct?

Well, suppose you were to sort the array row by row. I believe it would be correct to then say that the you can reduce each two dimensional array to a single one:
row = array[r]
sort(row);

Now, we can't be so direct when it comes to columns. Well, I can propose two solutions:

1. Create a new array "u" that can hold up to 5 elements. Store each element at each row that is at a specific column and sort that array. Then, restore it back into original array.
2. Directly apply sort method to each column.

I will be writing down the code for it because I feel like it will reduce confusion compared to if I explained it with pseudocode.

For the first method, you would do something like:

for(int i = 0; i < 5; ++i) {
int u[] = new int[5];
for(int j = 0; j < 5; j++) {
u[j] = array[j][i];
}
sort(u);
for(int j = 0; j < 5; j++) {
array[j][i] = u[j];
}
}

For the second method, you would do something like:

for(int i = 0; i < 5; i++) {
for(int j = 0; j < 4; j++) {
int k = j + 1;
for(int k = j+1; k > -1 && array[k][i] < array[j][i]; k--) { // insertion sort
swap(array[k][i], array[j][i]);
}
}
}

sabsa
12-16-2011, 09:13 AM
thank you so much for helping.I'll try that.

what I'm writing is that attachment.
the first one I'm writing in what you said.and the second one is what I'm write before.
is this writing right?
what should I do next?