Skip to content

Commit 0af6e98

Browse files
authored
Add diagonalSort function for matrix sorting
Implement diagonal sorting for a matrix.
1 parent c9bb2fe commit 0af6e98

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* @param {number[][]} mat
3+
* @return {number[][]}
4+
*/
5+
var diagonalSort = function(mat) {
6+
const m = mat.length;
7+
const n = mat[0].length;
8+
9+
for (let i = 0; i<m; i++){ // (i, 0)
10+
let x = i;
11+
let y = 0;
12+
13+
let arr = [];
14+
15+
while (x < m && y < n){
16+
arr.push(mat[x][y]);
17+
18+
x++;
19+
y++;
20+
}
21+
22+
arr.sort((a, b) => a-b);
23+
24+
x = i;
25+
y = 0;
26+
27+
for (let k = 0; k < arr.length; k++) {
28+
mat[x][y] = arr[k];
29+
30+
x++;
31+
y++;
32+
}
33+
}
34+
35+
for (let j = 1; j < n; j++) {
36+
let x = 0;
37+
let y = j;
38+
39+
let arr = [];
40+
41+
while (x < m && y < n) {
42+
arr.push(mat[x][y]);
43+
44+
x++;
45+
y++;
46+
}
47+
48+
arr.sort((a, b) => a - b);
49+
50+
x = 0;
51+
y = j;
52+
53+
for (let k = 0; k < arr.length; k++) {
54+
mat[x][y] = arr[k];
55+
56+
x++;
57+
y++;
58+
}
59+
}
60+
61+
return mat;
62+
};

0 commit comments

Comments
 (0)