- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
K-th Element of Two Sorted Arrays in C++
In this tutorial, we are going to write a program that finds the k-th element from thee merged array of two sorted arrays.
Let's see the steps to solve the problem.
- Initialise the two sorted arrays.
- Initialise an empty array of size m + n.
- Merge the two arrays into the new array.
- Return the k - 1 element from the merged array.
Example
Let's see the code.
#include <iostream> using namespace std; int findKthElement(int arr_one[], int arr_two[], int m, int n, int k) { int sorted_arr[m + n]; int i = 0, j = 0, index = 0; while (i < m && j < n) { if (arr_one[i] < arr_two[j]) { sorted_arr[index++] = arr_one[i++]; }else { sorted_arr[index++] = arr_two[j++]; } } while (i < m) { sorted_arr[index++] = arr_one[i++]; } while (j < n) { sorted_arr[index++] = arr_two[j++]; } return sorted_arr[k - 1]; } int main() { int arr_one[5] = {1, 3, 5, 7, 9}, arr_two[5] = {2, 4, 6, 8, 10}; int k = 7; cout << findKthElement(arr_one, arr_two, 5, 4, k) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
7
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
- Related Articles
- k-th missing element in sorted array in C++
- Find m-th smallest value in k sorted arrays in C++
- Merge k sorted arrays of different sizes in C++
- Median of Two Sorted Arrays in C++
- Merge two sorted arrays in C#
- Merge k sorted arrays in Java
- Merge two sorted arrays using C++.
- Find relative complement of two sorted arrays in C++
- Program to find out the k-th largest product of elements of two arrays in Python
- N-th multiple in sorted list of multiples of two numbers in C++
- K-th Greatest Element in a Max-Heap in C++
- k-th missing element in an unsorted array in C++
- Merging two unsorted arrays in sorted order in C++.
- Merge two sorted arrays in Java
- Sorted Arrays in C++

Advertisements