Jump to content

Merge sort

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Danakil (talk | contribs) at 16:07, 2 September 2004. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer science, merge sort or mergesort is a sort algorithm for rearranging lists (or any other data structure that can only be accessed sequentially, e.g. file streams) into a specified order. It is a particularly good example of the divide and conquer algorithmic paradigm.

Conceptually, merge sort works as follows :

  1. Divide the unsorted list into two sublists of about half the size
  2. Sort each of the two sublists
  3. Merge the two sorted sublists back into one sorted list.


Analysis

Merge sort has an average and worst-case performance of O(n·log(n)). In the worst case, mergesort does about 30% less comparisons than quicksort does in the average case, thus mergesort very often needs to make fewer comparisons than quicksort. However, its overhead is slightly higher than quicksort's (it does more element movement) and, depending on the data structure to be sorted, may take more memory (though this is becoming less and less of a consideration for commonly available hardware and typical data). It is also much more efficient than quicksort if the data to be sorted can only be efficiently accessed sequentially, and is thus popular in languages such as Lisp where sequentially accessed data structures are very common. Unlike quicksort, merge sort is a stable sort.

More precisely, merge sort does between ⌈ n·log(n) - n + 1 ⌉ and ⌈ n·log(n) - 0.914·n ⌉ comparisons in the worst case.

Merge sorting tape drives

Merge sort is so inherently sequential that it's practical to run it using slow tape drives as input and output devices. It requires very little memory, and the memory required does not change with the number of data elements. If you have four tape drives, it works as follows:

  1. divide the data to be sorted in half and put half on each of two tapes
  2. merge individual pairs of records from the two tapes; write two-record chunks alternately to each of the two output tapes
  3. merge the two-record chunks from the two output tapes into four-record chunks; write these alternately to the original two input tapes
  4. merge the four-record chunks into eight-record chunks; write these alternately to the original two output tapes
  5. repeat until you have one chunk containing all the data, sorted --- that is, for lg n passes, where n is the number of records.

On tape drives that can run both backwards and forwards, you can run merge passes in both directions, avoiding rewind time. For the same reason it is also very useful for sorting data on disk that is too large to fit entirely into primary memory.

Optimizing merge sort

This might seem to be of historical interest only, but on modern computers, locality of reference is of paramount importance in software optimization, because multi-level memory hierarchies are used. In some sense, main RAM can be seen as a slow tape drive, level 3 cache memory as a slightly faster one, level 2 cache memory as faster still, and so on. In some circumstances, cache reloading might impose unacceptable overhead and a carefully crafted merge sort could have considerable running time improvement. This opportunity might change if fast memory becomes very cheap again, or if exotic architectures like the Tera MTA become commonplace.

Designing a merge sort to perform optimally often requires adjustment to available hardware, eg. number of tape drives, or size and speed of the relevant cache memory levels.

External Resources

Sample implementations

  def sort == tree:merge,⟨⟩⟩ ° α:[id]
  sort []  = []
  sort [a] = [a]
  sort x   = merge (sort left) (sort right)
           where
              left  = [x!n | n <- [0..mid]]
              right = [x!n | n <- [(mid+1)..max]
              max   = #x - 1
              mid   = max div 2
def mergesort(a):
  if len(a) <= 1: return a
  mid = len(a) // 2
  return merge (mergesort(a[0:mid]), mergesort(a[mid:]))
void merge_sort (float v[], int start, int end) {
	int mid;		
	if (start == end) return;	
	if (start == end - 1) return;	
	mid = (start + end) / 2;
	merge_sort (v, start, middle);
	merge_sort (v, mid , end);
	merge (v, start, mid , end);
}