MergeSort Algorithm

1) Cut the array in half.

2) Sort the left half.

3) Sort the right half.

4) Merge the two sorted halves into one sorted array.

 

// CODE
// Recursive merge sort algorithm

template 
void  MergeSort  ( ItemType  values[ ] ,  int  first ,  int  last )		
//  Pre:   first <= last
//  Post: Array values[first..last] sorted into 
//    ascending order.
{
	if  ( first < last ) 	           //  general case
	{	
      int  middle = ( first  +  last ) / 2  ;
		MergeSort ( values, first, middle ) ;		
		MergeSort( values,  middle + 1, last ) ;

		// now  merge two subarrays
		// values  [ first . . . middle ] with 
		// values [ middle + 1,  . . . last ].

		Merge(values,  first, middle, middle + 1, last);
	}           
} 	





Running Time

The entire array can be subdivided into halves only log2N times.

Each time it is subdivided, function Merge is called to re-combine the halves.

Function Merge uses a temporary array to store the merged elements.

Merging is O(N) because it compares each element in the subarrays.

Copying elements back from the temporary array to the values array is also O(N).

MergeSort is O(N*logN).

link to site with example code

 

 

© Lynne Grewe