Consider the two-dimensional array A [1..n, 1..m] with integer elements.
Compose a program that will rearrange the columns of the matrix A so that the elements on its last line to either in ascending order by the method of selection. The modified picture will be displayed on the screen.
For example :
I see it.
you need to store this data transposed, and sort it row-wise which c++ can do easily.
if you store it 'normally' it will be a lot more trouble.
(yes, I just stated in english what the above code does).
if you MUST use a 2-d array, you can still load it trasnposed and sort the rows (which are actually the columns).
for ( i=n-1; i<n; i++ ){ // there is only one iteration: with i == n-1
for ( j=0; j<m; j++ ){
for ( ni = i; ni<n; ni++ ){ // there is only one iteration: with ni == n-1
for ( nj = j; nj<m; nj++ ){
Therefore, you have loops that very little and can be take out:
1 2 3 4
i = n-1;
for ( j=0; j<m; j++ ){
ni = i; // but this is always the same and thus can be done outside
for ( nj = j; nj<m; nj++ ){
Second, your lines 28-30 swap values of elements A[ni][nj] and A[i][j]
Therefore, you essentially have:
1 2 3 4 5 6 7 8
int row = n-1;
for ( j=0; j<m; j++ ) {
for ( nj = j; nj<m; nj++ ) {
if ( A[row][j] > A[row][nj] ) {
// swap A[row][j] and A[row][nj]
}
}
}
Yes, you sort the last row. You swap elements of the last row.
But you want to swap entire columns:
1 2 3 4 5 6 7 8
int last = n-1;
for ( j=0; j<m; j++ ) {
for ( nj = j; nj<m; nj++ ) {
if ( A[last][j] > A[last][nj] ) {
// swap column j with column nj
}
}
}
You have to swap elements on every row of the array, not just on the last.