## Two Sub-Quadratic Sorts

### October 30, 2009

There’s not much to say about either comb sort or shell sort, so they are presented below without comment. You may find it instructive to compare them to the sort functions of the previous exercise.

`function sort(A,n, gap,i,switched,t) {`

gap = n

do {

if (gap > 1)

gap = int(gap / 1.3)

switched = 0

for (i=1; i<=n-gap; i++)

if (A[i+gap] < A[i]) {

t = A[i]; A[i] = A[i+gap]; A[i+gap] = t

switched = 1 }

} while (switched || gap > 1) }

`function sort(A,n, gap,i,j,t) {`

while (gap < n)

gap = 3 * gap + 1

while (gap > 1) {

gap = int(gap / 3)

for (i=gap+1; i<=n; i++) {

t = A[i]

for (j=i; gap<j && t<A[j-gap]; j-=gap)

A[j] = A[j-gap]

A[j] = t } } }

Comb sort has been proven to have *O*(*n* log *n*) performance, regardless of the gap sequence, and shell sort has been proven to be somewhat worse, though the hidden constant factors make the two competitive in practice. Either is suitable for a general-purpose sort function, though you should also consider some of the other sorting algorithms we will examine as this series continues.

The code, including the test suite of the previous exercise, is collected at http://programmingpraxis.codepad.org/XysypyUa, but you can’t run it, since codepad doesn’t provide an Awk interpreter.

Pages: 1 2

[…] […]

[…] Praxis – Two Sub-Quadratic Sorts By Remco Niemeijer In yesterday’s Programming Praxis problem we have to implement two sort algorithms. Let’s get […]

My Haskell solution (see http://bonsaicode.wordpress.com/2009/10/31/programming-praxis-two-sub-quadratic-sorts/ for a version with comments):

shell sort implemented in c

Your analysis is wrong for comb sort!. See http://cstheory.stackexchange.com/questions/9619/analysis-of-comb-sort . The answers on the link I just gave are referring to a link that says that COMB SORT CANNOT RUN FASTER THAN O(N^2). Do you have any source that says that comb sort runs in sub quadratic time?