Algorithm Ch 3 Lec 2
Algorithm Ch 3 Lec 2
Each set is individually sorted, and the resulting sorted sequences are
merged to produce a single sorted sequence of n elements.
9/25/2024
ALGORITHM FOR MERGE SORT
Algorithm MergeSort(low,high)
//a[low:high] is a global array to be sorted
//Small(P) is true if there is only one element
//to sort. In this case the list is already sorted.
{
if (low<high) then //if there are more than one element
{
//Divide P into subproblems
//find where to split the set
mid = [(low+high)/2];
//solve the subproblems.
Mergesort (low,mid);
Mergesort(mid+1,high);
//combine the solutions .
Merge(low,mid,high);
}
9/25/2024
9/25/2024
Tree of Calls of MergeSort (1,10)
9/25/2024
Time Anlysis (MergeSort)
The computing time for merge sort is described by the recurrence relation:
In Quick sort, the division into 2 sub arrays is made so that the sorted sub
arrays do not need to be merged later.
9/25/2024
Worst Case Analysis of Quicksort
Worst case: sorted array! — O(n2)
CW(n) = (n+1) + n + … + 2
= (n+1)(n+2)/2
Cworst(n) = O(n2)
9/25/2024
Average Case Analysis of Quicksort
Average case: random arrays —O(n log n)
# CA(n) is much less than CW(n)
# Under the assumption that partitioning element v has
an equal probability of being the ith smallest element
# CA (n) = O (n log n)
9/25/2024
Comparison between Mergesort and QuickSort
Experiments •
# Comparison between QuickSort and MergeSort on
Sun 10/30
#Data made by random integer generator
#Average-case on 50 random inputs
9/25/2024
Thank You