Find!!
# of comparison and exchange will be represented by Big-O notation!
Length of list : n j-th pass of comparison : from index i = 0 to I = n-1-j where n is the length of the list. Compares adjacent items and exchanges those that are Out of order. After each pass, we can get the next largest value. How to exchange two items -> swap function! void swap( int& val1, int& val2 ) { int temp = val1; val1 = val2; val2 = temp; } void swap( int& val1, int& val2 ) { val1 = val1 ^ val2; val2 = val1 ^ val2; val1 = val1 ^ val2; } General swapping XOR swapping
54321 when sort a collection of items to replace ascending order, worst case is placement of item that is ordered by descending order
passcomparisonexchange 0N-11 1N-21 2N-31 3N-41 ⋮⋮⋮ N-111
passcomparisonexchange ⋮⋮⋮ nnn
First phase. Split list into two sublists recursively Second phase. merge two sub lists into one sorted list recursively
Sub list Sub list Merge i = 0 ; j = 0 ; While( i <= sublist1.length && j <= sublist2.length ) if( sublist1[i] <= sublist2[j] copy sublist1[i] to Merge[k]; increase i; else copy sublist2[j] to Merge[k]; increase j; increase k; end
How is the complexity of Merge sort ? – Consider total # of comparison when merging occurs