Java Program to Sort 2D Array Across Columns
Last Updated :
18 Mar, 2022
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here. This program is used to Sort the 2D array Across Columns. We will use the concept of vector to sort each column.
Algorithm:
- Traverse each column one by one.
- Add elements of Column 1 in vector v.
- Sort the vector.
- Push back the sorted elements from vector to column.
- Empty the vector by removing all elements for fresh sorting.
- Repeat the above steps until all columns are done.
Illustration: Creating a Vector
Here we are creating a default vector of the initial capacity is 10 so do the syntax is as follows:
Vector<E> v = new Vector<E>();
Functions that will be used in order to achieve the goal are as follows:
A. removeAll(): The java.util.vector.removeAll(Collection col) method is used to remove all the elements from the vector, present in the collection specified.
Syntax:
Vector.removeAll(Vector)
B. Collections.sort(): This method is used to sort the vector.
Syntax:
Collections.sort(Vector)
C. add(): This method is used to add elements in the vector.
Syntax:
Vector.add(value)
D. get(): This method will get the element of Vector stored at a particular index
Syntax:
Vector.get(3);
Example
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
public static void main(String[] args)
throws java.lang.Exception
{
int [][] arr = { { 7 , 2 , 0 , 5 , 1 },
{ 3 , 8 , 2 , 9 , 14 },
{ 5 , 1 , 0 , 5 , 2 },
{ 4 , 2 , 6 , 0 , 1 } };
System.out.println( "Matrix without sorting \n" );
for ( int i = 0 ; i < 4 ; i++) {
for ( int j = 0 ; j < 5 ; j++) {
System.out.print(arr[i][j] + " " );
}
System.out.println();
}
Vector<Integer> v = new Vector<>();
for ( int i = 0 ; i < 5 ; i++) {
for ( int j = 0 ; j < 4 ; j++) {
v.add(arr[j][i]);
}
Collections.sort(v);
for ( int j = 0 ; j < 4 ; j++) {
arr[j][i] = v.get(j);
}
v.removeAll(v);
}
System.out.println( "Matrix after sorting \n" );
for ( int i = 0 ; i < 4 ; i++) {
for ( int j = 0 ; j < 5 ; j++) {
System.out.print(arr[i][j] + " " );
}
System.out.println();
}
}
}
|
Output
Matrix without sorting
7 2 0 5 1
3 8 2 9 14
5 1 0 5 2
4 2 6 0 1
Matrix after sorting
3 1 0 0 1
4 2 0 5 1
5 2 2 5 2
7 8 6 9 14
Auxiliary Space : O(1)
Share your thoughts in the comments
Please Login to comment...