Merge sort
Merge Sort Merge sort is an efficient sorting algorithm that combines two sorted subarrays to form a larger sorted array. It employs a divide-and-conquer ap...
Merge Sort Merge sort is an efficient sorting algorithm that combines two sorted subarrays to form a larger sorted array. It employs a divide-and-conquer ap...
Merge Sort
Merge sort is an efficient sorting algorithm that combines two sorted subarrays to form a larger sorted array. It employs a divide-and-conquer approach, dividing the input array into smaller subarrays until each subarray contains only one element. The subarrays are then merged together in a way that preserves the sorting order.
Step 1: Divide
Choose a pivot element from the input array. This element will divide the array into two halves, one containing elements less than the pivot and the other containing elements greater than the pivot.
The pivot itself becomes the first element in the sorted subarray.
Step 2: Conquer
Recursively apply the divide-and-conquer approach to the two subarrays created by the pivot.
These subarrays are now sorted in ascending order.
Step 3: Merge
Merge the two sorted subarrays together, starting from the first elements.
The elements are compared in order, and the smaller element is added to the output array.
The process continues until one of the subarrays is empty.
Example
Suppose the input array [8, 3, 7, 9, 1] is divided into two subarrays: [8, 3] and [7, 9, 1].
Merge:
The pivot is 8.
[3, 8] is merged into the output array.
[7, 9, 1] is merged into the output array.
Time Complexity
Merge sort has a time complexity of O(n log k), where n is the length of the input array and k is the length of the subarray. This is because the algorithm divides the input array into approximately k subarrays, each of which is roughly half the size of the input array. Therefore, the number of comparisons required to merge the subarrays is roughly equal to n log k.
Advantages
Merge sort is highly efficient for large input arrays.
It has a time complexity that is nearly linear in the best case.
It is easy to implement.
Disadvantages
Merge sort is not as efficient for small input arrays.
It can be sensitive to the choice of pivot element