This program is utilized to Sort the 2D exhibit Across lines. We will utilize the idea of vector to sort each column.
Vector
Vector(): Creates a default vector of the initial capacity is 10. Vector v = new Vector();
Functions we will use in this:
1. removeAll(): The java.util.vector.removeAll(Collection col) technique is utilized to eliminate every one of the components from the vector, present in the assortment indicated.
Syntax:
Vector.removeAll(Vector)
2. Collections.sort(): This method is used to sort the vector.
Syntax:
Vector.removeAll(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:
Implementation:
Example
// 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 readibility System.out.println(); // Creating an object of Vector class Vector 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(); } } }
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
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.