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.

 Live Demo

#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.

Updated on: 09-Apr-2021

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements