Merge sort in Coldfusion

For far too long I’ve been using Bubble sorts, they’re very basic and very slow but mainly I’ve been sorting tiny little arrays or lists and the server just don’t care about it.

But that’s not the proper way of doing things. Now I don’t really understand sorting algorithms all that much so I use this site to work out which one I want to use, plus a little bit of wiki:

I’ve decided to use merge sort from now on mainly because it’s quite fast and although it generally seems to be a tiny bit slower than a shell or heap sort, it is stable which shell and heap are not. I don’t really know what that means but it sounds safe! Also it works much better on large sets than any of the simple algorithms.

The algorithm is more complex than a Bubble sort and although I understand the gist of it I decided to find someone elses code and use that. So I did.

Simon Horwith’s blog entry on search algorithms

This guy has made a fantastic little demo app, very comprehensive, with 6 different sortin algorithms in it. You can download the zip and drop it into a server and test the speeds of each algorithm. Then the code is there for you to play with, or as Simon put it: I look forward to hearing how people put them to use as well as any other findings with them.

I’ve tweaked his code a bit, so it will take an array of structures/objects, and sort by any publically accessible field of the that structure. Here’s how I’ve used it in the test page:

sort = new mergesort();

a = {}; = 'Pete';
a.age = 27;

b = {}; = 'Holly';
b.age = 22;

c = {}; = 'Jesus';
c.age = 2012;

peeps = [a,b,c];


Original array


// sort peeps array, by into Descending (default) order
peeps = sort.sortArrayByFieldAscending(peeps,'name');


Sorted by name in descending (default) order


// sort peeps array, by oject.age into Ascencing order
peeps = sort.sortArrayByFieldAscending(peeps,'age',true);


Sorted by age in ascending order


You can view the live demo of it working here and I’ve also attached a .zip of the .cfm and .cfc.

The ZIP link above doesn’t work at the moment, I’ll have it fixed shortly!

Thanks to Simon Horwith, and hopefully someone else will find this useful!

3 thoughts on “Merge sort in Coldfusion

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s