forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
706a917
commit 21c58d6
Showing
1 changed file
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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) | ||
* | ||
*/ |