8. Mergesort & Quicksort
27/02/23
Divide-and-Conquer
- General algorithm design paradigm
- Divide - Divide the input data in two disjoint subsets and
- Recur - Solve the subproblems associated with and
- Conquer - Combine the solutions for and into a solution for
- Base case is either size 0 or 1
Merge Sort
- On an input sequence (array/list) with elements consists of three steps:
- Divide - Partition into two sequences and of about elements each
- Recur - Recursively sort and
- Conquer - Merge and into a unique sorted sequence
Merge-Sort Tree
- An execution of merge-sort is depicted by a binary tree
- each node represents a recursive call of merge-sort and stores
- unsorted sequences before the execution and its partition
- sorted sequence at the end of the execution
- the root is the initial call
- the leaves are calls on sub sequences of size 0 or 1
- each node represents a recursive call of merge-sort and stores
Analysis of Merge-Sort
- The height of the merge-sort tree is )
- The overall amount of work done at all the nodes at depth is
- partition and merge sequences of size
- make recursive calls
- numbers all occur and are used at each depth
- Thus, the total running time of the merge sort is
Quick-sort
- In mergesort the divide is simple but the merge is complicated. Quicksort replaces the merge part
- When the lists A and B are sorted and known to be in disjoin ordered ranges
- If A and B are stored as consecutive sub-arrays, then merge actually needs no work at all, just forget the boundary
3-way split
- Quick-sort is a randomised sorting algorithm based on the divide-and-conquer paradigm
- Divide - pick a random element (pivot) and partition into
- elements less than
- elements equal to
- elements greater than
- Recur - sort and
- Conquer - join
- Divide - pick a random element (pivot) and partition into
2-way split
- Divide - pick a random element (pivot) and partition into
- $L$ elements less than $x$
- $GE$ elements greater than or equal to$x$ - Recur - sort and
- Conquer - join
Partitions of Lists
- If storing as separate structures, we partition an input sequence as follows:
- Remove, in turn, each element from and
- Insert into or depending on the result of the comparison with the pivot
- Each insertion and removal is at the beginning (or end) of the sequence, and hence takes time
- Thus, the partition step of quick-sort takes time
In-place - Means they only a little extra space is used to store data elements