35: Implement Merge Sort
⏳⌚ 00:00:00

Question:-

Sort given array using merge sort.
Example 1:
Input:
N=6
arr[] = {3, 2, 9 , 1, 15, 10}
Output: {1, 2, 3, 9, 10, 15}
Example 2:
Input:
N=4
arr[] = {15. -2, 1, 18}
Output: {-2, 1, 15, 18}

Steps to solve:-

1. Function merge:-The merge function takes an integer array arr[], the left index left, the middle index mid, and the right index right as parameters. It performs the merging step by merging two subarrays arr[left..mid] and arr[mid+1..right] into a single sorted subarray.
2. Function mergeSort:-The mergeSort function takes an integer array arr[], the left index left, and the right index right as parameters. It recursively divides the array into two halves until it reaches subarrays with only one element. Then, it merges these subarrays back together in sorted order.
3. Merge Operation:- The merging step (handled by the merge function) involves: Creating temporary arrays leftArr and rightArr to store the elements of the left and right subarrays. Copying data from the main array arr[] into these temporary arrays. Merging the elements from the temporary arrays back into the main array while maintaining the order.
4. Main Function:- In the main function: An integer array arr is declared with unsorted elements. The size n of the array is calculated. The original array is displayed. The mergeSort function is called to sort the array in ascending order using the Merge Sort algorithm. The sorted array is displayed.

solution->

View Code 1
Time Complexity = O(N log(N))
Space Complexity = O(n)