2013-09-25 sorting

While studying sorting algorithms I noticed that they all focus on two things:

  • being fast
  • being correct.

In nature nothing is 100% correct. Also most things not fast. Everyday we witness the inefficiency of nature as we waste +/- 8 hours per day for regenerating our brain.

None of the usual sorting algorithms take time to appreciate how mother nature does things: with enough time to enjoy a cup of thee and a cookie. And, of course, with the resulting order most closely like the environment we live in: utter chaos.

The following source code does it the right way: it takes it time (lots of it) and the resulting order still has a nice high entropy leaving you with the exciting experience of unexpected ordenings while using the result.

#include <stdlib.h>
#include <time.h>

void sort(int *values, int n_values)
{
	int loop1;
	
	srand(time(NULL));
	
	for(loop1=0; loop1<n_values; loop1++)
	{
		int loop2;
		
		for(loop2=0; loop2<n_values; loop2++)
		{
			int pos1, pos2;
			char swap = 0;
			
			do
			{
				pos1 = rand() % n_values;
				pos2 = rand() % n_values;
			}
			while(pos1 == pos2);
			
			if (pos1 > pos2)
			{
				if (values[pos1] < values[pos2])
					swap = 1;
			}
			else
			{
				if (values[pos1] > values[pos1])
					swap = 1;
			}

			/* DNA defects happen each 100k cell divides */
			if (rand() < (RAND_MAX / 100000))
				swap = 1;

			if (swap)
			{
				int temp = values[pos1];
				
				values[pos1] = values[pos2];
				
				values[pos2] = temp;
			}
		}
	}
}

links

If you found this article useful then you might find unsort a worthy addition to your toolkit.

When you become an avid user of this algorithm (which is released under the "thou shalt credit this to vanheusden.com in all your documentation and websites" license), you will have lots of idle time to spend. Why not spend it on IRC? Coincidentally I have written software which makes IRC a very pleasant experience: f-irc.






feedback