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
// Java Program to Sort the 2D array Across Rows // Importing required libraries import java.io.*; import java.lang.*; import java.util.*; // Main class public class GFG { // Main driver method public static void main(String[] args) throws java.lang.Exception { // Custom input 2D matrix int [][] arr = { { 1 , 8 , 4 , 7 , 3 }, { 8 , 3 , 1 , 7 , 5 }, { 6 , 2 , 0 , 7 , 1 }, { 2 , 6 , 4 , 1 , 9 } }; // Display message only System.out.println( "Matrix without sorting \n" ); // Print and display the matrix before sorting // using nested for loops for ( int i = 0 ; i < 4 ; i++) { for ( int j = 0 ; j < 5 ; j++) { // Printing the matrix elements System.out.print(arr[i][j] + " " ); } // New line as we are finished with one row System.out.println(); } // New line for better readability System.out.println(); // Creating an object of Vector class Vector<Integer> v = new Vector<>(); for ( int i = 0 ; i < 4 ; i++) { for ( int j = 0 ; j < 5 ; j++) { // Adding elements of row in vector v.add(arr[i][j]); } // Elements in vector gets sorted Collections.sort(v); for ( int j = 0 ; j < 5 ; j++) { // Sorted elements are pushed back from // vector to row arr[i][j] = v.get(j); } // Elements are removed from vector for fresh // sorting v.removeAll(v); } // Display message only System.out.println( "Matrix after sorting \n" ); // Print and display the matrix after sorting // using nested for loops for ( int i = 0 ; i < 4 ; i++) { for ( int j = 0 ; j < 5 ; j++) { // Printing the matrix elements System.out.print(arr[i][j] + " " ); } // New line as we are finished with one row System.out.println(); } } } |
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