There are multiple approaches to do this, Here I'm sharing follow two methods by which it can be achieved.
- Using Comparator Arrays.sort : An built-in feature of Java.
- Using Merge Sort
Using Comparator Arrays.sort : A built-in feature of Java.
import java.util.Arrays;
class Array2D {
public static void printTwoDimensionArray(int [][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
public static void main(String [] args) {
int [][] arr = {
{1, 2},
{6, 8},
{4, 7},
{9, 11},
{7, 10},
{13, 16},
{5, 9},
{8, 9},
{10, 11}
};
Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));
printTwoDimensionArray(arr);
}
}
Using Merge Sort
import java.util.ArrayList;
class MergeSortComparator {
public static void printSingleDimensionArray(int [] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void printDoublyDimensionArray(int [][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
public static void merge(int[][] arr, int start, int mid, int end, int index) {
int i, j, k;
int n1 = mid - start + 1;
int n2 = end - mid;
int columnLength = arr[0].length;
int [][] leftSubArray = new int [n1][columnLength];
int [][] rightSubArray = new int [n1][columnLength];
// Copy elements to Temp LeftSubArray
for (i = 0; i < n1; i++) {
for (j = 0; j < columnLength; j++) {
leftSubArray[i][j] = arr[start + i][j];
}
}
// Copy elements to Temp RightSubArray
for (i = 0; i < n2; i++) {
for (j = 0; j < columnLength; j++) {
rightSubArray[i][j] = arr[mid + 1 + i][j];
}
}
i = j = k = 0;
while(i < n1 && j < n2) {
if (leftSubArray[i][index] <= rightSubArray[j][index]) {
arr[start + k] = leftSubArray[i];
i++;
} else {
arr[start + k] = rightSubArray[j];
j++;
}
k++;
}
while(i < n1) {
arr[start + k] = leftSubArray[i];
i++;
k++;
}
while(j < n2 && (start + k) < end) {
arr[start + k] = rightSubArray[j];
j++;
k++;
}
}
public static void mergeSort(int[][] arr, int start, int end, int index) {
if (start >= end) {
return;
}
int mid = (start + end) / 2;
mergeSort(arr, start, mid, index);
mergeSort(arr, mid + 1, end, index);
merge(arr, start, mid, end, index);
return;
}
public static void main(String [] args) {
int [][] arr = {
{1, 2},
{6, 8},
{4, 7},
{9, 11},
{7, 10},
{13, 16},
{5, 9},
{8, 9},
{10, 11}
};
int m = arr.length;
int n = arr[0].length;
// Last argument as Index is set to 0,
mergeSort(arr, 0, m-1, 0);
printDoublyDimensionArray(arr);
}
}
Double.compare(b[0], a[0])
instead. – Nessim