-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthelementinMatrix.cpp
More file actions
60 lines (56 loc) · 1.4 KB
/
Copy pathKthelementinMatrix.cpp
File metadata and controls
60 lines (56 loc) · 1.4 KB
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
// Implemented by Kritagya Kumra
//{ Driver Code Starts
// kth largest element in a 2d array sorted row-wise and column-wise
// #include<bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 1000
// int mat[MAX][MAX];
int kthSmallest(int mat[MAX][MAX], int n, int k);
// driver program to test above function
int main()
{
// int t;
// cin >> t;
// while (t--)
// {
// int n;
// cin >> n;
// for (int i = 0; i < n; i++)
// for (int j = 0; j < n; j++)
// cin >> mat[i][j];
// int r;
// cin >> r;
// cout << kthSmallest(mat, n, r) << endl;
// }
int mat[MAX][MAX] = {{16, 28, 60, 64}, {22, 41, 63, 91}, {27, 50, 87, 93}, {36, 78, 87, 94}};
cout << kthSmallest(mat, 4, 3) << endl;
// cout << "7th smallest element is " << kthSmallest(mat, 4, 7);
return 0;
}
// } Driver Code Ends
int kthSmallest(int Mat[MAX][MAX], int N, int k)
{
vector<int> temp;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
temp.push_back(Mat[i][j]);
}
}
sort(temp.begin(), temp.end());
int counter = 0;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
Mat[i][j] = temp[counter];
counter++;
}
}
return Mat[0][k - 1];
}
// Implemented by Kritagya Kumra