forked from keshavagarwal17/All-Cp-Algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkthElement.cpp
68 lines (57 loc) · 1.44 KB
/
kthElement.cpp
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
// K-th element of two sorted Arrays
/* Question - Given two sorted arrays arr1 and arr2 of size N and M respectively and an element K. The task is to find the element that would be at the k’th position of the final sorted array. */
#include <bits/stdc++.h>
using namespace std;
int kthElement(int arr1[], int arr2[], int n, int m, int k)
{
int i=0,j=0,l=1;
while(i<n && j<m)
{
if(arr1[i] < arr2[j])
{
if(k==l)
return arr1[i];
l++;
i++;
}
else if(arr1[i] > arr2[j])
{
if(k==l)
return arr2[j];
j++;
l++;
}
else
{
if(k==l)
return arr1[i];
if(k==l+1)
return arr1[i];
i++;
j++;
l+=2;
}
}
while(i<n)
{
if(k==l)
return arr1[i];
i++;
l++;
}
while(j<m)
{
if(k==l)
return arr2[j];
j++;
l++;
}
return -1;
}
int main()
{
int arr1[] = {2, 3, 6, 7, 9};
int arr2[] = {1, 4, 8, 10};
cout << (kthElement(arr1,arr2,5,4,5)) << endl;
return 0;
}