Professional Documents
Culture Documents
Algorithm:
1. Divide the array in to two halves.
2. Recursively sort the first n/2 items.
3. Recursively sort the last n/2 items.
4. Merge sorted items (using an auxiliary array).
MergeSort:
Let’s design the algorithm top-down. We’ll assume that the
procedure that merges two sorted list is available to us.
We’ll implement it later. Because the algorithm is called
recursively on sub lists, in addition to passing in the array
itself, we will pass in two indices, which indicate the first and
last indices of the sub array that we are to sort.
Contd
8
Merging: All that is left is to describe the procedure that merges two
sorted lists. Merge(A, p, q, r) assumes that the left sub array,
A[p::q], and the right sub array, A[q+1::r], have already been sorted.
We merge these two sub arrays by copying the elements to a
temporary working array called B. For convenience, we will
assume that the array B has the same index range A, that is, B[p::r].
(One nice thing about pseudo-code, is that we can make these
assumptions, and leave them up to the programmer to figure out
how to implement it.)
Contd
13
Swap the root node with the lowest, right most node
and delete the lowest, right most value; insert the
deleted value in the array in its proper position;
adjust the heap tree; and repeat this process until the
tree is empty.
21
Contd
Contd
22
Contd
23
Contd
24
Contd
25
Contd
26
3.4. Quick Sort
27
Divide: The divide step just computes the middle of the sub
arXiv:1406.4399, 2014.
41