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 by MFI highest to lowest within each locus
  • 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): https://stackblitz.com/edit/js-complex-sort.

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>