Slide 10
Slide 10
Merge Sort
► Merge sort is yet another sorting algorithm that falls under the category of
Divide and Conquer technique. It is one of the best sorting techniques that
successfully build a recursive algorithm.
Divide and Conquer Strategy
► After splitting the arrays into two halves, the next step is to conquer. In
this step, we individually sort both of the subarrays A[p..q] and A[q+1,
r]. In case if we did not reach the base situation, then we again follow
the same procedure, i.e., we further segment these subarrays followed
by sorting them separately.
Combine
► Step4: Next, we will merge them back in the same way as they were
broken down.
► Step5: For each list, we will first compare the element and then
combine them to form a new sorted list.
► Step6: In the next iteration, we will compare the lists of two data
values and merge them back into a list of found data values, all placed
in a sorted manner.
Analysis of Merge Sort:
► Let T (n) be the total time taken by the Merge Sort algorithm.
► Sorting two halves will take at the most 2T time.
► When we merge the sorted lists, we come up with a total n-1
comparison because the last element which is left will need to be
copied down in the combined list, and there will be no comparison.
► Thus, the relational formula will be
Continued…
► But we ignore '-1' because the element will take some time to be
copied in merge lists.
Continued…
► Best Case Complexity: The merge sort algorithm has a best-case time
complexity of O(n*log n) for the already sorted array.
► Average Case Complexity: The average-case time complexity for the
merge sort algorithm is O(n*log n), which happens when 2 or more
elements are jumbled, i.e., neither in the ascending order nor in the
descending order.
► Worst Case Complexity: The worst-case time complexity is
also O(n*log n), which occurs when we sort the descending order of
an array into the ascending order.
► Space Complexity: The space complexity of merge sort is O(n).
Merge Sort Applications