Development PHP

Authored by Corey Ballou

A Quick Implementation of String Sort in PHP

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

Although much faster than version 1, even a user defined quicksort implementation in PHP cannot compare to that of sort.

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.

Author: Corey Ballou

Corey Ballou is the CEO of Whether you're a student, young professional, entrepreneur, startup, or small business, you can be up and online fast with your own custom domain, email, and webpage on POP. Corey is a professional PHP developer by trade, specializing in custom web applications development for startups, small businesses, and agencies. Follow Corey on Twitter @cballou.