sorting algorithm that repeatedly divides an un-sorted section into two equal sub-sections, sorts them separately and merges them correctly. 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. 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. 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) Example: Program: Output: 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. Applications: ■ 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.
■ Organize an MP3 library. ■ Display Google PageRank results.