22 November 2010 One of the nice things about building sortvis.org and writing the posts that led up to it is that people email me with pointers to esoteric algorithms I've never heard of. Today's post is dedicated to one of these - a curious little sorting algorithm called cyclesort . It was described in 1990 in a 3-page paper by B.K. Haddon , and has become a firm favourite of mine. Cyclesort has some nice properties - for certain restricted types of data it can do a stable, in-place sort in linear time, while guaranteeing that each element will be moved at most once.
Read full article from cortesi - Cyclesort - a curious little sorting algorithm
# Sort an array in place and return the number of writes. def cycleSort(array): writes = 0 # Loop through the array to find cycles to rotate. for cycleStart in range(0, len(array) - 1): item = array[cycleStart] # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # If the item is already there, this is not a cycle. if pos == cycleStart: continue # Otherwise, put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 # Rotate the rest of the cycle. while pos != cycleStart: # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # Put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 return writesAlso refer to http://en.wikipedia.org/wiki/Cycle_sort
Read full article from cortesi - Cyclesort - a curious little sorting algorithm