Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet
Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet
Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Merge sort is a balanced binary tree method that first breaks a list up recursively<br />
into two lists until each sublist has only one element. Then the sublists are<br />
recombined, two at a time and sorted order, until only one sorted list remains.<br />
Note: The height <strong>of</strong> the tree formed in merge sort is O(log 2 n) for n elements.<br />
Notes:<br />
10, 4, 7, 1<br />
10, 4 7, 1<br />
10 4 7 1<br />
4, 10 1, 7<br />
1, 4, 7, 10<br />
• First three rows do the sublist splitting.<br />
• Last two rows do the merging.<br />
• There are two distinct algorithms at work.<br />
81<br />
!<br />
procedure merge_sort(L = " a<br />
# i<br />
if n > 1 then<br />
m := 7n/28<br />
!<br />
L 1 := " a i<br />
m<br />
$<br />
%<br />
# &i=1<br />
n<br />
$<br />
%<br />
&i=m+1<br />
n<br />
$<br />
% )<br />
&i=1<br />
!<br />
L 2 := " a<br />
# i<br />
L := merge(merge_sort(L 1 ), merge_sort(L 2 ))<br />
!<br />
{L is now the sorted " a<br />
# i<br />
n<br />
$<br />
% }<br />
&i=1<br />
procedure merge(L 1 , L 2 : sorted lists)<br />
L := /<br />
while L 1 and L 2 are both nonempty<br />
remove the smaller <strong>of</strong> the first element <strong>of</strong> L 1 and L 2 and append it to<br />
end <strong>of</strong> L<br />
if either L 1 or L 2 are empty, append the other list to the end <strong>of</strong> L<br />
{L is the merged, sorted list}<br />
82