Merge two sorted arrays in O(1) extra space using Heap

Merge two sorted arrays in O(1) extra space using Heap

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Given two sorted arraysarr[]brr[] of size N, and M, the task is to merge the two given arrays such that they form a sorted sequence of integers combining elements of both the arrays.

Examples:

Input:_ arr[] = {10}, brr[] = {2, 3}_

Output: 2 3 10

Explanation:_ The merged sorted array obtained by taking all the elements from the both the arrays is {2, 3, 10}._

Therefore, the required output is 2 3 10.

Input:_ arr[]__= {1, 5, 9, 10, 15, 20}, brr[] = {2, 3, 8, 13}_

Output:_ 1 2 3 5 8 9 10 13 15 20_

Naive Approach: Refer to Merge two sorted arrays for the simplest approach to merge the two given arrays.

_Time Complexity: _O(N * M)

Auxiliary Space:_ O(1)_

Space Optimized Approach: Refer to Merge two sorted arrays with O(1) extra space to merge the two given arrays without using any extra memory.

Time Complexity:_ O(N * M)_

Auxiliary Space:_ O(1)_

Efficient Space Optimized Approach: Refer to Efficiently merging two sorted arrays with O(1) extra space to merge the two given array without using any extra memory.

Time Complexity:_ O((N + M) * log(N + M))_

Auxiliary Space:_ O(1)_

Heap** – based Approach:** The problem can be solved using Heap. The idea is to traverse arr[] array and compare the value of arr[i] with brr[0] and check if arr[i] is greater than brr[0] *or not. If found to be true then *swap(arr[i], brr[0) and perform the heapify operation on brr[]. Follow the steps below to solve the problem:

  • Traverse the array arr[] and compare the value of arr[i] with brr[0] and check if arr[i] is greater than brr[0] or not. If found to be true then swap(arr[i], brr[0) and perform the heapify operation on brr[].
  • Finally, sort the array brr[] and print both array.

Below is the implementation of the above approach:

  • C++

// C++ program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Function to perform min heapify

// on array brr[]

**void** minHeapify(``**int** brr[], **int** i, **int** M)

{

// Stores index of left child

// of i.

**int** left = 2 * i + 1;

// Stores index of right child

// of i.

**int** right = 2 * i + 2;

// Stores index of the smallest element

// in (arr[i], arr[left], arr[right])

**int** smallest = i;

// Check if arr[left] less than

// arr[smallest]

**if** (left < M && brr[left] < brr[smallest]) {

// Update smallest

smallest = left;

}

// Check if arr[right] less than

// arr[smallest]

**if** (right < M && brr[right] < brr[smallest]) {

// Update smallest

smallest = right;

}

// if i is not the index

// of smallest element

**if** (smallest != i) {

// Swap arr[i] and arr[smallest]

swap(brr[i], brr[smallest]);

// Perform heapify on smallest

minHeapify(brr, smallest, M);

}

}

// Function to merge two sorted arrays

**void** merge(``**int** arr[], **int** brr[],

**int** N, **int** M)

{

// Traverse the array arr[]

**for** (``**int** i = 0; i < N; ++i) {

// Check if current element

// is less than brr[0]

**if** (arr[i] > brr[0]) {

// Swap arr[i] and brr[0]

swap(arr[i], brr[0]);

// Perform heapify on brr[]

minHeapify(brr, 0, M);

}

}

// Sort array brr[]

sort(brr, brr + M);

}

// Function to print array elements

**void** printArray(``**int** arr[], **int** N)

{

// Traverse array arr[]

**for** (``**int** i = 0; i < N; i++)

cout << arr[i] << " "``;

}

// Driver Code

**int** main()

{

**int** arr[] = { 2, 23, 35, 235, 2335 };

**int** brr[] = { 3, 5 };

**int** N = **sizeof**``(arr) / **sizeof**``(arr[0]);

**int** M = **sizeof**``(brr) / **sizeof**``(brr[0]);

// Function call to merge

// two array

merge(arr, brr, N, M);

// Print first array

printArray(arr, N);

// Print Second array.

printArray(brr, M);

**return** 0;

}

Output:

2 3 5 23 35 235 2335

Time Complexity:_ O((N + M) * log (M))_

Auxiliary Space:_ O(1)_

Efficient Approach: Refer to merge two sorted arrays to efficiently merge the two given arrays.

_Time Complexity: _O(N + M)

Auxiliary Space:_ O(N + M)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

arrays divide and conquer heap mathematical sorting amazon amdocs array-merge brocade goldman sachs heap sort juniper networks priority-queue snapdeal

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Merge two sorted arrays in O(1) extra space using QuickSort partition

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Kth smallest element from an array of intervals

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Merge Sort Program in Java: Difference Between Merge Sort & Quicksort

In this tutorial, we'll learn Merge Sort Program in Java: Difference Between Merge Sort & Quicksort. Find out carefully. It will help your projects complete quickly.

Heap Sort Explained

As you may know, heapsort is also one of the most asked sorting algorithms besides mergesort and quicksort and today we’re going to talk.

Print X array elements closest to the Kth smallest element in the array

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.