Merge
Sorting
Divide and Conquer Strategy
Group Members
• Aniqa Fatima (SP23-BSE-002)
• Maryam Shabbir (SP23-BSE-012)
• Hammad Khawar (SP23-BSE-006)
What Is Merge Sort?
• It is a recursive sorting algorithm that works on Divide-and-
Conquer Strategy.
• Divide: The algorithm starts with breaking up the array into
smaller and smaller pieces.
• Conquer: The algorithm merges the small pieces of the array
back together
Algorithm of Merge Sort
1. If the array has one or zero elements, it is already sorted; return.
2. Find the middle index of the array.
3. Recursively apply Merge Sort to the left and right halves of the
array.
4. Merge the two sorted halves into a single sorted array:
•Initialize two pointers, one for each half.
•Compare the elements at the pointers and copy the smaller one
to the result.
•Move the pointer of the array from which the element was taken.
•Repeat until all elements from both halves are merged.
Pseudo-Code
MergeSort(arr[], left, right){
if(left < right){
mid = (left+right)/2;
MergeSort(arr[], Ieft, mid);
MergeSort(arr[], mid+1,
right);
Merge(arr, l, mid, right);
}
Pros and Cons of Merge Sort
Advantages Disadvantages
• Efficient for large datasets • Requires additional space for
temporary arrays
• Stable:
Maintains the relative order of equal • Recursive nature may lead to stack
elements. overflow in case of large datasets
• Works well for linked lists • Slower for smaller datasets compared
to simpler algorithms like Insertion
Sort
Time and Space Complexity
Time Space
• Auxiliary Space: O(n)
• Splitting the array: O(log n)
Temporary arrays needed for merging.
levels.
• In-Place Sorting: No
• Merging at each level: O(n). Requires extra space compared to
algorithms like Quick Sort.
• Total O(n log n). • Recursion Stack Space: O(log n)
Depth of recursion is proportional to
log(n).
Thank you