Merge sort is a divide and conquer algorithm that divides an array into halves, recursively sorts the halves, and then merges the sorted halves back together. The key steps are:
1. Divide the array into equal halves until reaching base cases of arrays with one element.
2. Recursively sort the left and right halves by repeating the divide step.
3. Merge the sorted halves back into a single sorted array by comparing elements pairwise and copying the smaller element into the output array.
Merge sort has several advantages including running in O(n log n) time in all cases, accessing data sequentially with low random access needs, and being suitable for external sorting of large data sets that do not fit in memory
3. Topics to be covered:
■ Introduction
■ Definition
■ Algorithm
■ Steps involved
■ Program
■ Applications
4. Introduction:
■ Merge Sort is a complex and fast sorting
algorithm that repeatedly divides an un-
sorted section into two equal sub-
sections, sorts them separately and
merges them correctly.
5. Definition:
■ Merge sort is a DIVIDE AND CONQUER
algorithm. It divides input array in two
halves, calls itself for the two halves and
then merges the two sorted halves.The
merge() function is used for merging two
halves.
6. Steps involved:
– Divide the problem into sub-problems that
are similar to the original but smaller in size.
– Conquer the sub-problems by solving them
recursively. If they are small enough, just
solve them in a straightforward manner.
– Combine the solutions to create a solution to
the original problem.
7. Algorithm:
mergeSort(arr[], l, r)
If l < r
1. Find the middle point to divide the array into
two halves: middle m = (l+r)/2
2. Call mergeSort for first half: Call
mergeSort(arr, l, m)
3. Call mergeSort for second half: Call
mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
14. Why Merge Sort??
■ Compared to insertion sort merge sort is
faster.
■ On small inputs, insertion sort may be faster.
But for large enough inputs, merge sort will
always be faster, because its running time
grows more slowly than insertion sorts.
15. ■ Merge sort type algorithms allows large data
sets to be sorted easily.
■ Merge sort accesses data sequentially and the
need of random access is low.
■ Inversion count problem.
■ Used in External Sorting.
Applications: