Home Web Front-end JS Tutorial Merge Sort Demystified: A Beginner&#s Guide to Divide and Conquer Sorting

Merge Sort Demystified: A Beginner&#s Guide to Divide and Conquer Sorting

Sep 12, 2024 pm 08:17 PM

Merge Sort Demystified: A Beginner

Merge Sort was introduced by John von Neumann in 1945, primarily to improve the efficiency of sorting large datasets. Von Neumann's algorithm aimed to provide a consistent and predictable sorting process using the divide and conquer method. This strategy allows Merge Sort to handle both small and large datasets effectively, guaranteeing a stable sort with a time complexity of O(n log n) in all cases.

Merge Sort employs the divide and conquer approach, which splits the array into smaller subarrays, recursively sorts them, and then merges the sorted arrays back together. This approach breaks the problem into manageable chunks, sorting each chunk individually and combining them efficiently. As a result, the algorithm performs well even on large datasets by dividing the sorting workload.

Recursion is a process where a function calls itself to solve a smaller version of the same problem. It keeps breaking the problem down until it reaches a point where the problem is simple enough to solve directly, which is called the base case.

Below is an implementation of Merge Sort in JavaScript, showing how the array is recursively split and merged:

function mergeSort(arr) {
    if (arr.length <= 1) return arr;

    const mid = Math.floor(arr.length / 2);
    const left = mergeSort(arr.slice(0, mid));
    const right = mergeSort(arr.slice(mid));

    return merge(left, right);
}

function merge(left, right) {
    let result = [];
    while (left.length && right.length) {
        if (left[0] < right[0]) result.push(left.shift());
        else result.push(right.shift());
    }
    return result.concat(left, right);
}

Copy after login

To better understand how Merge Sort works, let's walk through the process using the array: [38, 27, 43, 3, 9, 82, 10]

Step 1: Recursive Division (mergeSort function)
The array is recursively split into smaller subarrays until each subarray has only one element. This happens through the following lines in the mergeSort function:

function mergeSort(arr) {
    if (arr.length <= 1) return arr;
Copy after login

That stops our recursion.

Here’s how the recursive division unfolds:

  • Initial Call: mergeSort([38, 27, 43, 3, 9, 82, 10])
    • The array is split at the midpoint: [38, 27, 43] and [3, 9, 82, 10]
  • First Half:

    • mergeSort([38, 27, 43])
      • Split at the midpoint: [38] and [27, 43]
    • mergeSort([27, 43])
      • Split into [27] and [43]
    • Subarrays [38], [27], and [43] are now individual elements and ready to be merged.
  • Second Half:

    • mergeSort([3, 9, 82, 10])
      • Split at the midpoint: [3, 9] and [82, 10]
    • mergeSort([3, 9])
      • Split into [3] and [9]
    • mergeSort([82, 10])
      • Split into [82] and [10]
    • Subarrays [3], [9], [82], and [10] are now ready to be merged.

Step 2: Merging the Sorted Subarrays (merge function)
Now, we start merging the subarrays back together in sorted order using the merge function:

function merge(left, right) {
    let result = [];
    while (left.length && right.length) {
        if (left[0] < right[0]) result.push(left.shift());
        else result.push(right.shift());
    }
    return result.concat(left, right);
}

Copy after login

Here’s how the merging process works:

First Merge (from the base cases):

  • Merge [27] and [43] → Result is [27, 43]
  • Merge [38] with [27, 43] → Result is [27, 38, 43]

At this point, the left half of the array is fully merged: [27, 38, 43].

Second Merge (from the base cases):

  • Merge [3] and [9] → Result is [3, 9]
  • Merge [82] and [10] → Result is [10, 82]
  • Merge [3, 9] with [10, 82] → Result is [3, 9, 10, 82]

Now, the right half is fully merged: [3, 9, 10, 82].

Step 3: Final Merge
Finally, the two halves [27, 38, 43] and [3, 9, 10, 82] are merged using the merge function:

Compare 27 (left[0]) and 3 (right[0]). Since 3 < 27, add 3 to the result.
Compare 27 and 9. Add 9 to the result.
Compare 27 and 10. Add 10 to the result.
Compare 27 and 82. Add 27 to the result.
Compare 38 and 82. Add 38 to the result.
Compare 43 and 82. Add 43 to the result.
Add the remaining element 82 from the right array.
The fully merged and sorted array is:
[3, 9, 10, 27, 38, 43, 82].

Time Complexity: Best, Average, and Worst Case: O(n log n)
Let's look at it closer:

Dividing (O(log n)): Each time the array is split into two halves, the size of the problem is reduced. Since the array is divided in half at each step, the number of times you can do this is proportional to log n. For example, if you have 8 elements, you can divide them in half 3 times (since log₂(8) = 3).

Merging (O(n)): After dividing the array, the algorithm merges the smaller arrays back together in order. Merging two sorted arrays of size n takes O(n) time because you have to compare and combine each element once.

Overall Complexity (O(n log n)): Since dividing takes O(log n) steps and you merge n elements at each step, the total time complexity is the multiplication of these two: O(n log n).

Space Complexity: O(n)
Merge Sort requires extra space proportional to the size of the array because it needs temporary arrays to store the elements during the merge phase.

Comparison to Other Sorting Algorithms:
QuickSort: While QuickSort has an average time complexity of O(n log n), its worst case can be O(n^2). Merge Sort avoids this worst-case scenario, but QuickSort is generally faster for in-memory sorting when space is a concern.
Bubble Sort: Much less efficient than Merge Sort, with a time complexity of O(n^2) for average and worst-case scenarios.

Real World Usage
Merge Sort is widely used for external sorting, where large datasets need to be sorted from disk, as it efficiently handles data that doesn’t fit into memory. It's also commonly implemented in parallel computing environments, where subarrays can be sorted independently, taking advantage of multi-core processing.

Moreover, libraries and languages such as Python (Timsort), Java, and C (std::stable_sort) rely on variations of Merge Sort to ensure stability in sorting operations, making it particularly suitable for sorting objects and complex data structures.

Conclusion
Merge Sort continues to be a fundamental algorithm in both theoretical computer science and practical applications due to its stability, consistent performance, and adaptability for sorting large datasets. While other algorithms like QuickSort may perform faster in certain situations, Merge Sort’s guaranteed O(n log n) time complexity and versatility make it invaluable for memory-constrained environments and for maintaining the order of elements with equal keys. Its role in modern programming libraries ensures it remains relevant in real-world applications.

Sources:

  1. Knuth, Donald E. The Art of Computer Programming, Vol. 3: Sorting and Searching. Addison-Wesley Professional, 1997, pp. 158-160.
  2. Cormen, Thomas H., et al. Introduction to Algorithms. MIT Press, 2009, Chapter 2 (Merge Sort), Chapter 5 (Algorithm Complexity), Chapter 7 (QuickSort).
  3. Silberschatz, Abraham, et al. Database System Concepts. McGraw-Hill, 2010, Chapter 13 (External Sorting).
  4. "Timsort." Python Documentation, Python Software Foundation. Python's Timsort
  5. "Java Arrays.sort." Oracle Documentation. Java's Arrays.sort()

The above is the detailed content of Merge Sort Demystified: A Beginner&#s Guide to Divide and Conquer Sorting. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles