Sorting algorithms can be difficult, but I gave it a crack and here’s what I produced

I find sorting algorithms difficult. I also find recursion algorithms difficult (that’s another story). My brain isn’t really wired very well for algorithmic thinking, which is probably an odd thing for a software developer to say.

My day job today required me to write a reasonably complex sorting algorithm in JavaScript on a data set that required grouping and multiple layers of sub-sorting. Conceptually it’s actually relatively easy – as this answer on StackOverflow suggests – but life is never that simple.

In order to focus on just the algorithm during development, I coded it in StackBlitz, a relatively new online IDE/sandpit for JavaScript based projects.
Below is my running example, developed with TypeScript. All up it took me about 6 hours (including understanding the requirements, a couple of missteps, and cleaning up the code, then refactoring into modules/files).

If the data names seem strange that’s because it’s for biological data. I’ve left out all the unnecessary fields and focused purely on the fields that need sorting (except for the ID and Rnd fields).

I’ve added the sorting requirements into the code, but here’s what we needed (exactly as received):

  • Group by DSA Category (Specific first, Potential next)
  • Then Group by Locus, get the highest MFI for each locus, and sort locus by highest MFI to lowest
  • Then sort antibody (the same antibody should be grouped together) by MFI highest to lowest.
    [JS: Another way of looking at it: Group by locus, and find the highest MFI for each locus. Then within each locus group by antibody. Then sort antibody within each locus by MFI, highest to lowest. Then step back up to locus and based on the highest MFI found within the locus, sort each locus “group” by that MFI, from highest to lowest.]
  • Then sample date


Running Example

NOTE: You can pop the editor open in a new window by selecting “Edit On StackBlitz” in the bottom-left of the inserted window.
Select the folded-page icon at the top of the left column (below the StackBlizt blue/white icon) to see the list of files.
The code is split over multiple .ts (TypeScript) files, and index.ts is the starting point.

If you’re using Internet Explorer or there’s just a black window below, here’s the link to the code (and I suggest using a “modern” browser – Chrome and Edge both work):

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.