forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSort_2D_Array.java
82 lines (74 loc) · 2.07 KB
/
Sort_2D_Array.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* We are given a 2D array of order N X M and a column number K ( 1<=K<=m). Our task is to sort the 2D array according to values in the Column K.
Examples:
Input : If our 2D array is given as (Order 4X4)
39 27 11 42
10 93 91 90
54 78 56 89
24 64 20 65
Sorting it by values in column 3
Output : 39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90
*/
import java.util.*;
class Sort_2D_Array {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows and columns");
int m = sc.nextInt();
int n = sc.nextInt();
int arr[][] = new int[m][n];
System.out.println("Enter the elements of the array");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
arr[i][j] = sc.nextInt();
System.out.println("Enter the column to be sorted");
int k = sc.nextInt();
sort(arr, k, m);
}
public static void sort(int[][] arr, int col, int row) {
int max = 0, ind = -1;
for (int j = 0; j < row - 1; j++) {
max = arr[j][col];
ind = -1;
for (int i = (j + 1); i < row; i++) {
if (arr[i][col] > max) {
max = arr[i][col];
ind = i;
}
}
if (ind != -1) {
for (int k = 0; k <= col; k++) {
int temp = arr[j][k];
arr[j][k] = arr[ind][k];
arr[ind][k] = temp;
}
}
}
for (int[] x: arr) {
for (int y: x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
/*Enter number of rows and columns
4
4
Enter the elements of the array
39 27 11 42
10 93 91 90
54 78 56 89
24 64 20 65
Enter the column to be sorted
3
10 93 91 90
54 78 56 89
24 64 20 65
39 27 11 42
Space Complexity : O(1)
Time Complexity : O(m^2)
*
*/