Merge Sort: SCJ2013 Data Structure & Algorithms
Merge Sort: SCJ2013 Data Structure & Algorithms
Merge Sort: SCJ2013 Data Structure & Algorithms
Merge Sort
Divide
Sort
and
merge
Merge Sort Implementation
MergeSort() function
mergeSort(theArray,0,2); mergeSort(theArray,3,5);
merge(theArray,0,2,5);
2. mergeSort(theArray,0,2); 9. mergeSort(theArray,3,5);
16. merge(theArray,0,5);
[email protected]
mergeSort [38 16 27 39 12 27]
T
Unsorted data [38 16 27 39 12 27 ]
h
e Content of divided sublist with first=0 & last=5 [38 16 27 39 12 27 ]
Content of divided sublist with first=0 & last=2 [38 16 27 ]
E Content of divided sublist with first=0 & last=1 [38 16 ]
x Content of divided sublist with first=0 & last=0 [38 ]
e Content of divided sublist with first=1 & last=1 [16 ]
c Content of merged list with first=0 & last=1 [16 38 ]
u Content of divided sublist with first=2 & last=2 [27 ]
Content of merged list with first=0 & last=2 [16 27 38 ]
t
Content of divided sublist with first=3 & last=5 [39 12 27 ]
i Content of divided sublist with first=3 & last=4 [39 12 ]
o Content of divided sublist with first=3 & last=3 [39 ]
n Content of divided sublist with first=4 & last=4 [12 ]
Content of merged list with first=3 & last=4 [12 39 ]
R Content of divided sublist with first=5 & last=5 [27 ]
e Content of merged list with first=3 & last=5 [12 27 39 ]
s Content of merged list with first=0 & last=5 [12 16 27 27 38 39 ]
u
Sorted data [12 16 27 27 38 39 ]
l Press any key to continue . . .
t
Merge Sort Analysis
The list is always divided into two balanced list (or almost
balanced for odd size of list)
The number of calls to repeatedly divide the list until there is
one item left in the list is:
Assuming that the left segment and the right segment of the
list have the equal size (or almost equal size), then x lg n .
The number of iteration is approximately n lg n
Merge Sort Analysis
The same number of
repetition is needed
to sort and merge the
list.
Thus, as a whole the
number of steps
needed to sort data
using merge sort is 2n
lg n, which is
O(n lg n).
Mergesort
Analysis
Worst case: O(n * log2n)
Average case: O(n * log2n)
Performance is independent of the initial order of the array items
Advantage
Mergesort is an extremely fast algorithm
Disadvantage
Mergesort requires a second array (temporary array) as
large as the original array
References
1. Frank M. Carano, Janet J Prichard. Data
Abstraction and problem solving with C++
Walls and Mirrors. 5th edition (2007).
Addision Wesley.
2. Nor Bahiah et al. Struktur data & algoritma
menggunakan C++. Penerbit UTM, 2005.
12/10/2011 16