Week13 Lecture 38
Week13 Lecture 38
Week13 Lecture 38
Sorting Algorithm
Week 13 – Lecture 38
Background
What is Recursion???
Selection Sort and Insertion Sort have a worst-case running time of O(n2).
As the size of input grows, insertion and selection sort can take a long
time to run. Merge sort, on the other hand, runs in O(n*log n) time in all
the cases.
Divide and Conquer
In Merge Sort, the given unsorted array with n elements is divided into n subarrays,
each having one element because a single element is always sorted in itself. Then, it
repeatedly merges these subarrays, to produce new sorted subarrays, and in the end,
one complete sorted array is produced.
1. We take a variable p and store the starting index of our array in this. And we take
another variable r and store the last index of the array in it.
2. Then we find the middle of the array using the formula (p + r)/2 mark the middle
index as q, and break the array into two subarrays, from p to q and from q + 1 to r
index.
3. Then we divide these 2 subarrays again, just like we divided our main array and
this continues.
4. Once we have divided the main array into subarrays with single elements, then we
start merging the subarrays.
Pseudocode
MergeSort (A, lb, ub)
{
If (lb <ub)
{
mid = (lb + ub)/2
mergesort ( A, lb, mid);
mergesort (A, mid+1, ub);
merge (A, lb, mid, ub);
}
}
Code for Merge
Merge (A, lb, mid, ub)
{
i = lb;
j = mid + 1;
k = lb;
while ( i < = mid && j <= ub)
{
if (a[i] <= a[j])
{
b[k] = a[i];
i++; k++;
}
else
{
b[k] = a[j];
j++; k++;
}
}
Code for Merge
if (i > mid)
{
while ( j <= ub)
{
b[k] = a[j]; j++; k++;
}
}
else {
while ( i<= mid)
{
b[k] = a[i];
i++;
k++;
}
}