Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Merge K Sorted Array using JavaScript
Next article icon

Merge K Sorted Array using JavaScript

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given K sorted arrays and our task is to merge them into a single sorted array in JavaScript.

Example:

Input: 
arrays = [[2, 4, 5],
[1, 3, 8],
[0, 7, 9]];

Output: [0, 1, 2, 3, 4, 5, 7, 8]

These are the following approaches:

Table of Content

  • Naive Approach
  • Divide and Conquer Approach
  • Min-Heap Approach

Naive Approach

In this approach, we will concatenate all k sorted arrays into a single array. After concatenation, we sort that single array to obtain a sorted array. The function mergeArrays merges multiple arrays into a single array. It iterates through each array in the input arrays, concatenating them into merged_arr. Finally, it sorts the merged_arr in ascending order and returns the result.

Example: The example below shows how to Merge K sorted array using Naive approach.

JavaScript
function merge(left, right) {     let merged = [];     let leftIndex = 0;     let rightIndex = 0;      while (leftIndex < left.length              && rightIndex < right.length) {         if (left[leftIndex] < right[rightIndex]) {             merged.push(left[leftIndex]);             leftIndex++;         } else {             merged.push(right[rightIndex]);             rightIndex++;         }     }      return merged.concat(left.slice(leftIndex))                  .concat(right.slice(rightIndex)); }  function mergeArrays(arrays) {     if (arrays.length === 0)          return [];     if (arrays.length === 1)          return arrays[0];     const middle = Math.floor(arrays.length / 2);     const left = arrays.slice(0, middle);     const right = arrays.slice(middle);     return merge(mergeArrays(left),                 mergeArrays(right)); }  let arrays = [[1, 3, 5], [2, 4, 6], [0, 7, 8]]; console.log(mergeArrays(arrays)); 

Output
[   0, 1, 2, 3, 4,   5, 6, 7, 9 ] 

Time Complexity: O(N log N), where N is the total number of elements in all arrays.

Space Complexity: O(N), where N is the total number of elements in all arrays.

Divide and Conquer Approach

In this approach, we starts by dividing the K sorted arrays into smaller subarrays. We will repeatedly divides the array until each subarrays has only one or two arrays to merge. After that we merge them in pairwise. This is done by comparing elements from each array and selecting the smallest one to be added to the merged array. We will continue this process until all subarrays are merged.

Example: The example below shows how to Merge K sorted array using Divide and Conquer approach.

JavaScript
function merge(left, right) {     let merged = [];     let leftIndex = 0;     let rightIndex = 0;      while (leftIndex < left.length                  && rightIndex < right.length) {         if (left[leftIndex] < right[rightIndex]) {             merged.push(left[leftIndex]);             leftIndex++;         } else {             merged.push(right[rightIndex]);             rightIndex++;         }     }      return merged.concat(left.slice(leftIndex))                  .concat(right.slice(rightIndex)); }  function mergeArrays(arrays) {     if (arrays.length === 0)          return [];     if (arrays.length === 1)          return arrays[0];     const middle = Math.floor(arrays.length / 2);     const left = arrays.slice(0, middle);     const right = arrays.slice(middle);     return merge(mergeArrays(left),                      mergeArrays(right)); }  let arrays = [[1, 3, 5], [2, 4, 6], [0, 7, 8]]; console.log(mergeArrays(arrays)); 

Output
[   0, 1, 2, 3, 4,   5, 6, 7, 8 ] 

Time Complexity: O(N log K), where N is the total number of elements and K is the number of arrays.

Space Complexity: O(K), where K is the number of arrays.

Min-Heap Approach

This approach utilizes a min-heap (or priority queue) to efficiently merge K sorted arrays. The idea is to insert the first element of each array into the heap. Then, we extract the minimum element from the heap and insert the next element from the array from which the minimum element was extracted. This process continues until all elements from all arrays are merged into a single sorted array.

Steps:

  • Create a min-heap.
  • Insert the first element of each array into the heap. Along with the element, store the index of the array it came from and the index of the element within that array.
  • While the heap is not empty:
  • Extract the minimum element from the heap.
  • Add this element to the result array.
  • Insert the next element from the array from which the extracted element came.
  • Continue the process until the heap is empty.
  • The result array will be the merged sorted array.

Example:

JavaScript
class MinHeap {     constructor() { this.heap = []; }      insert(node) {         this.heap.push(node);         this.bubbleUp();     }      bubbleUp() {         let index = this.heap.length - 1;         while (index > 0) {             let parentIndex = Math.floor((index - 1) / 2);             if (this.heap[index].value                 >= this.heap[parentIndex].value)                 break;             [this.heap[index], this.heap[parentIndex]] = [                 this.heap[parentIndex], this.heap[index]             ];             index = parentIndex;         }     }      extractMin() {         if (this.heap.length === 1)             return this.heap.pop();         const min = this.heap[0];         this.heap[0] = this.heap.pop();         this.sinkDown(0);         return min;     }      sinkDown(index) {         let leftChildIndex = 2 * index + 1;         let rightChildIndex = 2 * index + 2;         let smallest = index;          if (leftChildIndex < this.heap.length             && this.heap[leftChildIndex].value             < this.heap[smallest].value) {             smallest = leftChildIndex;         }          if (rightChildIndex < this.heap.length             && this.heap[rightChildIndex].value             < this.heap[smallest].value) {             smallest = rightChildIndex;         }          if (smallest !== index) {             [this.heap[index], this.heap[smallest]] =                 [this.heap[smallest], this.heap[index]];             this.sinkDown(smallest);         }     }      isEmpty() { return this.heap.length === 0; } }  function mergeKSortedArrays(arrays) {     const minHeap = new MinHeap();     const result = [];      // Insert the first element of each array into the heap     arrays.forEach((array, i) => {         if (array.length > 0) {             minHeap.insert({                 value: array[0],                 arrayIndex: i,                 elementIndex: 0             });         }     });      while (!minHeap.isEmpty()) {         // Extract the smallest element from the heap         const { value, arrayIndex, elementIndex }             = minHeap.extractMin();         result.push(value);          // Insert the next element from the same array into         // the heap         const nextElementIndex = elementIndex + 1;         if (nextElementIndex < arrays[arrayIndex].length) {             minHeap.insert({                 value:                     arrays[arrayIndex][nextElementIndex],                 arrayIndex: arrayIndex,                 elementIndex: nextElementIndex             });         }     }      return result; }  let arrays = [[2, 4, 5], [1, 3, 8], [0, 7, 9]]; console.log(mergeKSortedArrays(arrays)); 

Output
[   0, 1, 2, 3, 4,   5, 7, 8, 9 ] 

Next Article
Merge K Sorted Array using JavaScript

Y

yuvraj07
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-DSA

Similar Reads

    JavaScript- Merge two Sorted Arrays
    These are the following ways to merge two sorted arrays: 1. Using Two Pointers (Efficient For Large Arrays)This approach involves using two pointers, one for each array, and comparing their elements as you iterate through them. This method works efficiently in O(n + m) time, where n and m are the le
    3 min read
    Javascript Program to Merge 3 Sorted Arrays
    Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D. Examples: Input : A = [1, 2, 3, 4, 5] B = [2, 3, 4] C = [4, 5, 6, 7] Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7] Input : A = [1, 2, 3, 5] B = [6, 7, 8
    8 min read
    JavaScript - Sort an Array of Strings
    Here are the various methods to sort an array of strings in JavaScript1. Using Array.sort() MethodThe sort() method is the most widely used method in JavaScript to sort arrays. By default, it sorts the strings in lexicographical (dictionary) order based on Unicode values.JavaScriptlet a = ['Banana',
    3 min read
    JavaScript Array toSorted() Method
    The JS arr.toSorted() method rearranges the array elements alphabetically and returns a new sorted array.Sorting Array of StringsJavaScriptconst arr = ["JS", "HTML", "CSS"]; const arr1 = arr.toSorted(); console.log(arr); console.log(arr1);Output[ 'JS', 'HTML', 'CSS' ][ 'CSS', 'HTML', 'JS' ]Array.toS
    3 min read
    JavaScript Array sort() Method
    The JS array.sort() method rearranges the array elements alphabetically and returns a sorted array. It does not create a new array but updates the original array.Sorting Array of StringsJavaScript// Original array let ar = ["JS", "HTML", "CSS"]; console.log(ar); // Sorting the array ar.sort() consol
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences