Java Program to Sort the 2D Array Across Rows
Last Updated :
15 Sep, 2021
This program is used to Sort the 2D array Across rows. We will use the concept of vector to sort each row.
Vector
Vector(): Creates a default vector of the initial capacity is 10.
Vector<E> v = new Vector<E>();
Functions we will use in this:
1. 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)
2. Collections.sort(): This method is used to sort the vector.
Syntax:
Collections.sort(Vector)
3. add(): This adds up elements in the vector.
Syntax:
Vector.add(value)
4. get(): This method will get an element of Vector stored at a particular index.
Syntax:
Vector.get(element);
Algorithm:
- Traverse each row one by one.
- Add elements of Row 1 in vector v.
- Sort the vector.
- Push back the sorted elements from vector to row.
- Empty the vector by removing all elements for fresh sorting.
- Repeat the above steps until all rows are done.
Implementation:
Example
Java
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws java.lang.Exception
{
int [][] arr = { { 1 , 8 , 4 , 7 , 3 },
{ 8 , 3 , 1 , 7 , 5 },
{ 6 , 2 , 0 , 7 , 1 },
{ 2 , 6 , 4 , 1 , 9 } };
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();
}
System.out.println();
Vector<Integer> v = new Vector<>();
for ( int i = 0 ; i < 4 ; i++) {
for ( int j = 0 ; j < 5 ; j++) {
v.add(arr[i][j]);
}
Collections.sort(v);
for ( int j = 0 ; j < 5 ; j++) {
arr[i][j] = 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
1 8 4 7 3
8 3 1 7 5
6 2 0 7 1
2 6 4 1 9
Matrix after sorting
1 3 4 7 8
1 3 5 7 8
0 1 2 6 7
1 2 4 6 9
Share your thoughts in the comments
Please Login to comment...