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.
- Lower case to upper case - An interesting fact
- Why quicksort is better than mergesort ?
- Perform the given queries on the rooted tree
- C# | How to perform a specified action on each element of the List
- Perform DDoS attack using Torshammer
- std::transform() in C++ STL (Perform an operation on all elements)
- Middle of three using minimum comparisons
- 8085 program to perform AND operation in nibbles of 8 bit number
- Data Structure design to perform required operations
- Self-Balancing-Binary-Search-Trees (Comparisons)
- Comparisons involved in Modified Quicksort Using Merge Sort Tree
- Search an element in an unsorted array using minimum number of comparisons
- Perform n steps to convert every digit of a number in the format [count][digit]
- Maximum and minimum of an array using minimum number of comparisons
- SQL | Case Statement