Merge Sort
Prof. Nitin Paharia
introduction
• This algorithm is based on divide and conquer
problem solving technique.
• A divide-and-conquer algorithm works by
recursively breaking down a problem into two or
more sub-problems of the same or related type, until
these become simple enough to be solved directly
• In merge sort problem is divided into two sub-
problems
• Problem- array of data to be sorted
Working of merge sort
• Divide the array in half
How do we sort?
• Sort the left half Can we avoid
sorting?
How?
• Sort the right half
• Merge the two halves together
Working of merge sort
• Divide the array in half
• Sort the left half take the left half, and go back to step 1
Until?
• Sort the right half take the left half, and go back to step 2
Until?
• Merge the two halves together
• MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Divide
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) Conquer
Idea of Merging
say we have two sorted lists, how can we
efficiently merge them?
idea: compare the first element in each list to
each other, take the smallest and add to the
merged list -AND… repeat
merging sorted arrays
• -easy concept, tricky code
• lots of special cases:
– keep track of two indices to step through both arrays (the
“front” of each array)
– indices do not necessarily move at the same speed
– have to stop the loop when either index reaches the end of
their array
– the two arrays are not necessarily the same size
– what to do when you reach the end of one array but not the
other?
– copy from temp back into the array