There’s not a whole lot of PHP algorithms floating around. Perhaps people just rely upon the SPL. I had a curiosity to find a string sorting algorithm written in PHP and I didn’t find any non array-based solutions. The implementation I came up with this morning implements recursion, passing by reference, and string iteration. It’s worth noting that this is a horribly slow solution. For this reason I’ve included a very concise solution which is an order of magnitude faster as it uses a C implementation of quicksort which generally runs in O(nlogn). To make people aware of quicksort, I have also implemented a solution for string sorting. With that being said, this could be a fun exercise for students. Alternative solutions and runtime analysis are welcome in the comments section.
Version 1 (slow)
Let’s be honest, if I didn’t use a pre-existing algorithm to create a function, odds are it’s going to be slow. This implementation most closely resembles a version of Bubble Sort without comparing apples to apples.
Version 2 – Quicksort Implementation
Version 3 – Fast and Concise
This version, although utilizing some fairly heavy functions like split and implode, still outperforms both previous solutions. This is due to the fact it utilizes a small subset of PHP core functions. The core PHP functions have heavily optimized implementations which are written directly in C, meaning it’s nearly impossible to get much faster except in small edge cases.