next up previous contents
Next: Hash tables Up: Sorting Previous: Bin, Bucket, Radix Sorts   Contents

Other methods not based on comparison

It always pays to think about the data you are trying to sort. Imagine you know the keys are the numbers from 0 to 99. How would you sort those? Take a moment to think about it.

The answer is surprisingly simple. We know that we have 100 entries in the array and we know exactly which keys should go there and in which order. This is a very unusual situation as far as general sorting is concerned, yet it may well come up in every-day life. Rather than employing one of the comparison-bases sorting algorithms, in this situation we can do something much simpler as demonstrated by the picture.

\epsfig{file=figs/fig6-1.eps}
allocate array `result' of size `size';

for (i=0; i<size; i++) 
    result[a[i]] = a[i];

return result;

For once we did create a second array to hold the result but, as a matter of fact, we can do without that, although we have to be slightly more inventive for that.

\epsfig{file=figs/fig6-2.eps}
for (i=0; i<size; i++) { 
  while (a[i] != i) { 
    item temp = a[a[i]];
    a[a[i]] = a[i];
    a[i] = temp;
  }
}

This looks worse than it is, complexity-wise: the algorithm performs at most $ n-1$ swaps where $ n$ is the size of the array, since one item, namely a[a[i]] is always swapped into its final position. So at worst, it has complexity $ n$.

This should make it clear that in particular situations, sorting might be performed by much simpler (and quicker) means. Once again it is the responsibility of the program designer to take this possibility into account.


next up previous contents
Next: Hash tables Up: Sorting Previous: Bin, Bucket, Radix Sorts   Contents
Martin Escardo 2005-01-11