ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-213Merge Sort
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-213

    Data Structures & Algorithms

    Progress0 / 37 done
    Topics37
    1Abstract Data Types2Complexity Analysis3Big Oh Notation4Stacks (Linked Lists and Array Implementations)5Recursion and analyzing recursive algorithms6Divide and Conquer Algorithms7Sorting Algorithms8Selection Sort9Insertion Sort10Merge Sort11Quick Sort12Bubble Sort13Heap Sort14Shell Sort15Radix Sort16Bucket Sort17Queue18Dequeuer19Priority Queues (linked and array implementations of queues)20Linked List and Its Various Types21Sorted Linked List22Searching an Unsorted Array23Binary Search for Sorted Arrays24Hashing and Indexing25Open Addressing and Chaining26Trees and Tree Traversals27Binary Search Trees28Heaps29M-Way Trees30Balanced Trees31Graphs32Breadth-First Traversal33Depth-First Traversal34Topological Order35Shortest Path36Adjacency Matrix and Adjacency List Implementations37Memory Management and Garbage Collection
    5 min read
    Topic 10 of 37
    Topic Study Note Illustration
    10

    Merge Sort

    Visual Reference Sorting Algorithm Wikipedia Description : Merge sort is a classic divide-and-conquer sorting algorithm that splits an array into two halves, recursively sorts each half, and...

    Merge Sort

    Sorting algorithm
    Visual ReferenceSorting Algorithm
    Wikipedia

    Description: Merge sort is a classic divide-and-conquer sorting algorithm that splits an array into two halves, recursively sorts each half, and then merges the sorted halves back together. This approach ensures that the entire array is sorted in a systematic way.

    How It Works

    1. Divide: If the array has more than one element, split it into two halves.
    2. Conquer: Recursively sort both halves.
    3. Combine: Merge the two sorted halves into a single sorted array.

    Time Complexity

    • Worst Case: O(nlog⁡n)O(n \log n)O(nlogn)
    • Average Case: O(nlog⁡n)O(n \log n)O(nlogn)
    • Best Case: O(nlog⁡n)O(n \log n)O(nlogn) — merge sort always divides the array and merges, regardless of the initial order of elements.

    Space Complexity

    • Space Complexity: O(n)O(n)O(n) — merge sort requires additional space for the temporary arrays used during the merging process.

    Stability

    • Stability: Merge sort is a stable sorting algorithm, meaning that it preserves the relative order of equal elements.

    Example Code

    Here's a C++ implementation of merge sort:

    #include <iostream>
    using namespace std;
    
    void merge(int arr[], int left, int mid, int right) {
        int n1 = mid - left + 1; // Size of left subarray
        int n2 = right - mid;    // Size of right subarray
    
        int* L = new int[n1]; // Create left subarray
        int* R = new int[n2]; // Create right subarray
    
        // Copy data to temp arrays L[] and R[]
        for (int i = 0; i < n1; i++)
            L[i] = arr[left + i];
        for (int j = 0; j < n2; j++)
            R[j] = arr[mid + 1 + j];
    
        int i = 0; // Initial index of first subarray
        int j = 0; // Initial index of second subarray
        int k = left; // Initial index of merged subarray
    
        // Merge the temp arrays back into arr[left..right]
        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) {
                arr[k++] = L[i++];
            } else {
                arr[k++] = R[j++];
            }
        }
    
        // Copy the remaining elements of L[], if any
        while (i < n1)
            arr[k++] = L[i++];
    
        // Copy the remaining elements of R[], if any
        while (j < n2)
            arr[k++] = R[j++];
    
        delete[] L; // Free the temporary arrays
        delete[] R;
    }
    
    void mergeSort(int arr[], int left, int right) {
        if (left < right) {
            int mid = left + (right - left) / 2; // Prevent overflow
            mergeSort(arr, left, mid); // Sort first half
            mergeSort(arr, mid + 1, right); // Sort second half
            merge(arr, left, mid, right); // Merge the sorted halves
        }
    }
    
    int main() {
        int arr[] = {38, 27, 43, 3, 9, 82, 10};
        int n = sizeof(arr) / sizeof(arr[0]);
        mergeSort(arr, 0, n - 1);
    
        cout << "Sorted array: ";
        for (int i = 0; i < n; i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
    
        return 0;
    }
    

    Explanation of the Code

    1. Function Definitions:

      • merge: Merges two sorted subarrays into a single sorted array.
      • mergeSort: Recursively sorts the array by dividing it into two halves.
    2. Merging Process:

      • The merge function first calculates the sizes of the two subarrays and creates temporary arrays to hold the values.
      • It then copies the elements into these temporary arrays, compares the elements from both arrays, and merges them back into the original array.
    3. Recursive Sort:

      • The mergeSort function recursively splits the array until it reaches base cases (single-element arrays).
      • After sorting both halves, it calls the merge function to combine them back into a sorted array.
    4. Output: Finally, the program prints the sorted array.

    Conclusion

    Merge sort is an efficient and stable sorting algorithm, particularly suitable for large datasets. Its O(nlog⁡n)O(n \log n)O(nlogn) time complexity makes it faster than simpler algorithms like bubble sort and insertion sort for larger lists. However, its requirement for additional memory can be a downside in memory-constrained environments. Merge sort is often used in situations where stability is important, such as in external sorting scenarios where data does not fit into memory.

    ← Previous topic 9
    Insertion Sort
    Next topic 11 →
    Quick Sort

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    5mremaining
    776words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Data Structures & Algorithms