A matrix contains one or more rows and columns. This program is to sort the columns in ascending order.
Let the matrix be:
The matrix A is a 2×2 matrix, i.e. the matrix has two rows and two columns. Now, the individual column elements would be sorted in ascending order.
We can use any sorting technique like bubble sort, selection sort to sort the elements column-wise.
For the first column, the two elements of the column will be compared. As, 12>10, they are not in ascending order, they will be swapped with each other. And the matrix will be:
Similarly, the elements of the 2nd column will be compared. Here 15<20 so, they are already in ascending order. They will not be swapped therefore, after the sorting the matrix will be:
Input: A matrix
OUTPUT: Matrix after sorting columns
PROCESS:
Step 1: [Taking the inputs]
Read m, n [the rows and columns of the matrix]
For i=0 to m-1 repeat
For j=0 to n-1 repeat
Read a[i][j]
[End of ‘for’ loop]
[End of ‘for’ loop]
Step 2: [Sorting the rows and columns]
[sorting the columns in ascending order]
for j=0 to n-1 repeat
for i=0 to m-1 repeat
for k=i+1 to m-1 repeat
if b[i][j]>b[k][j] then
Set t<-b[i][j]
Set b[i][j]<-b[k][j]
Set b[k][j]<-t
[End of ‘if’]
[End of ‘for’ loop]
[End of ‘for’ loop]
[End of ‘for’ loop]
[printing the matrix after sorting the columns]
Print "After sorting the columns in ascending order:"
for i=0 to m-1 repeat
for j=0 to n-1 repeat
print b[i][j]
[End of ‘for’ loop]
Move to the next line
[End of ‘for’ loop]
Step 3: Stop.
TIME COMPLEXITY:
//sorting the columns in ascending order
for (j=0;j<n;++j) ------------------ O(n)
{ for (i=0;i<m;++i)--------------- O(m)
{ for (k=i+1;k<m;++k) ------- O(m-i-1)
{ if (b[i][j]>b[k][j])---------- O(c1)
{ t=b[i][j];
b[i][j]=b[k][j];
b[k][j]=t; }
}
}
}
Here c1 is constant so, the time complexity is O(n*m*(m-i-1)*c1) = O(n*).
If the value of m and n are equal, the time complexity can be defined as O().
Related
Contributed by