Merge Sort
The idea is simple!! Partition by Position
Last updated
The idea is simple!! Partition by Position
Last updated
Merge sort is a simplest sorting technique which adopts D&C strategy.
If the size of array is 2 , then one comparison is required to sort them.
If the size is less than 2, then return the array as such.
When the size is greater than 2, divide the array into two halves and (partition in the middle).
Sort them recursively
Merge the smaller sorted arrays into a single sorted one
Merge Procedure: Combine two sorted arrays into a single array. It is done as follows:
Two pointers are initialized to point to first elements of the array being merged.
The elements pointed are compared and the smaller is added to the final sorted array. Pointer of the smaller element is incremented to point to its immediate sucessor in the array it was copied from
Repeat the procedure (Step 2) until one of the array is completely exhausted
Then, copy the remaining elements of the other array to the end of the final sorted array.
Sorted Array 1
Sorted Array 2
Time Complexity of Merge Sort:
Let n represents the Input Size (Number of elements in the array) and key comparisons indicate the basic operation. Then, the recurrence relation is given as
denote number of comparisons performed during the merge stage. In the worst case, neither of two arrays become empty before the other one just contains on element. Example is shown below
Hence, in the worst case the number of key comparisons . Therefore, for n>2. According to Master's theorem