As we know, Mergesort is a divide and conquer algorithm that splits the array to halves recursively until it reaches an array of the size of 1, and after that it merges sorted subarrays until the original array is fully sorted. Typical implementation of merge sort works in O(n Log n) time in all three cases (best, average and worst).
We need to reduce the best case performance from O(n log n) to O(n).
The idea is to consider the case when array is already sorted. Before merging, just check if arr[mid] > arr[mid+1], because we are dealing with sorted subarrays. This will lead us to the recursive relation T(n) = 2*T(n/2) + 1 which can be resolved by the master’s theorem, so T(n) = n.
Input : 1 2 3 4 Subarrays with size of 1:|1||2| |3||4| Subarrays with size of 2: |1 2| |3 4| Output : 1 2 3 4 Input : 1 2 3 4 5 6 7 8 Subarrays with size of 1: |1||2| |3||4| |5||6| |7||8| Subarrays with size of 2: |1 2| |3 4| |5 6| |7 8| Subarrays with size of 4: |1 2 3 4| |5 6 7 8| Output : 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
This article is contributed by Shlomi Elhaiani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Why quicksort is better than mergesort ?
- Comparisons involved in Modified Quicksort Using Merge Sort Tree
- Perform K of Q queries to maximize the sum of the array elements
- When does the worst case of Quicksort occur?
- Case-specific Sorting of Strings
- Print a case where the given sorting algorithm fails
- Case-specific sorting of Strings in O(n) time and O(1) space
- Find a permutation that causes worst case of Merge Sort
- Can QuickSort be implemented in O(nLogn) worst case time complexity?
- QuickSort Tail Call Optimization (Reducing worst case space to Log n )
- Minimum swaps to make two arrays identical
- Remove elements to make array sorted
- Minimum increment operations to make K elements equal
- Minimum removals required to make ranges non-overlapping
- Count of available non-overlapping intervals to be inserted to make interval [0, R]
- Minimum operations to make frequency of all characters equal K
- Minimum number of elements to add to make median equals x
- Find whether it is possible to make array elements same using one external number
- Minimum increment/decrement operations required to make Median as X
- Minimum number of subtract operation to make an array decreasing