[Home]History of Merge sort

HomePage | Recent Changes | Preferences

Revision 9 . . (edit) October 29, 2001 3:31 pm by Kragen [Added commentary on the quality of the code.]
Revision 7 . . October 26, 2001 3:39 am by (logged).157.137.xxx [Added notes about mergesorting on tapes.]
  

Difference (from prior major revision) (minor diff)

Added: 9a10,44
Here's a terrible implementation of mergesort in Python:


def merge(array, start1, end1, start2, end2, output, outstart, cmp):
"""Merge two sorted sequences into a new sorted sequence.

Takes two sorted sequences 'array[start1:end1]' and
'array[start2:end2]' and merges them into a new sorted sequence,
which it places in the array 'output', starting at 'outstart'.

"""
while start1 != end1 or start2 != end2:
if start2 == end2 or (start1 != end1 and
not cmp(array[start1], array[start2])):
output[outstart] = array[start1]
start1 = start1 + 1
else:
output[outstart] = array[start2]
start2 = start2 + 1
outstart = outstart + 1

def mergesort(array, cmp=lambda x, y: x > y, scratch=None, start=None,
end=None):
"""The fastest stable sort for large data sets."""
if scratch is None: scratch = [0] * len(array)
if start is None: start = 0
if end is None: end = len(array)
if end - start > 1:
middle = (start + end) / 2
mergesort(array, cmp, scratch, start, middle)
mergesort(array, cmp, scratch, middle, end)
merge(array, start, middle, middle, end, scratch, start, cmp)
array[start:end] = scratch[start:end]



Changed: 22c57
This might seem to be of historical interest only, but on modern computers, [locality of reference]? is of paramount importance in software optimization, because we have deep [memory hierarchies]?. This might change if fast memory becomes very cheap again, or if exotic architectures like the [Tera MTA]? become commonplace.
This might seem to be of historical interest only, but on modern computers, [locality of reference]? is of paramount importance in software optimization, because we have deep [memory hierarchies]?. This might change if fast memory becomes very cheap again, or if exotic architectures like the [Tera MTA]? become commonplace.

HomePage | Recent Changes | Preferences
Search: