0% found this document useful (0 votes)
31 views3 pages

Naman Garg F4 Ds Lab Test Soln 1

The document describes a C++ program to find the kth smallest element in a 2D array. It takes the array, number of rows and columns, and k as input. It uses a binary search approach calling a function Elemnts_Greater to count elements greater than the mid element in each iteration to find the kth smallest element.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views3 pages

Naman Garg F4 Ds Lab Test Soln 1

The document describes a C++ program to find the kth smallest element in a 2D array. It takes the array, number of rows and columns, and k as input. It uses a binary search approach calling a function Elemnts_Greater to count elements greater than the mid element in each iteration to find the kth smallest element.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

9919103116

Naman garg
F4
DS LAB TEST
Soln 1
#include <bits/stdc++.h>
using namespace std;
int N=100;
vector<vector<int>>arr(N,vector<int>(N));

int Elemnts_Greater(int num, int n,int m) {


int ans = 0;

for (int i = 0; i < n; i++) {


if (arr[i][0] > num) {
return ans;
}
if (arr[i][m - 1] <= num) {
ans += n;
continue;
}
int greaterThan = 0;
for (int jump = n / 2; jump >= 1; jump /= 2) {
while (greaterThan + jump < m &&
arr[i][greaterThan + jump] <= num) {
greaterThan += jump;
}
}

ans += greaterThan + 1;
}
return ans;
}

int kthSmallest( int n ,int m, int k) {

int l = arr[0][0], r = arr[n - 1][m - 1];


while (l <= r) {
int mid = (l + r) / 2;
int tmp = Elemnts_Greater(mid,n,m);

if (tmp >= k)
r = mid - 1;
else
l = mid + 1;
}
return l;
}

int main()
{
cout<<"Enter m,n,k\n";
int m,n;
cin>>m>>n;
int k;
cin>>k;
cout<<"Enter Array\n";
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>arr[i][j];
}
}
cout <<k<<" smallest element is " << kthSmallest(n,m, k);
return 0;
}

You might also like