ArchiveAboutFeed

Advice for Implementing a Decent Quicksort in Clojure

Summary of a long article.

I want to explore how I can take responsibility for code development, while using an LLM when I get stuck. I describe how I wrote a decent version of quicksort in Clojure, with some advice in the form of questions I took from an LLM. It never showed or wrote code.

I also used it during the exploration and spec phase, but that is for another time.

Introduction

In the discussion whether LLMs in software development are dumbing developers down or not, there seems to be consensus that outsourcing your brain is usually not a good idea.

The problem with LLMs however is that they tend to make it super easy to do that. Give the prompt, sit back and relax, and in no time your coding task is done.

While this may lead to something that works, there are several potential problems with it:

  1. Since you haven't written the code yourself, it will be difficult to absorb and understand it
  2. If you haven't specified exactly what you want, and what it should adhere to, you might get something you didn't ask for
  3. How can you possibly verify that the result is doing what you think it should be doing?
  4. The sheer amount of code that can be written in a day increases a hundred-fold (or more), leading to all sorts of other problems down the line (e.g. try reviewing everything)
  5. Design and engineering decisions are taken away from you which might lead to dire consequences. Which might have been prevented had an experienced developer had thought about this first and then written the code

A steep reduction of cost per written line of code is great to have but might potentially cost a lot more down the line.

A future without human software development?

Again, there seem to be 2 main opposing views here. A large portion of the industry seems to assume that at some point software development is a solved problem, and human beings are not needed there. Instead, we all become product engineers and build amazing products using these tools.

An opposing view is that there are software engineers and companies that refuse to use LLMs for software engineering, precisely because of the problems mentioned above (plus moral, legal and environmental reasons not discussed here).

The best of both worlds?

Disregarding moral, legal and environmental discussions here, I wonder if the best of both views is a possibility to move forward. Neither machine nor human being is infallible. What if we take the strengths of human beings, add LLM based automation assistance for human weaknesses and find a way to get the best of both worlds?

This might lead to the following principles:

  1. The software engineer (SE) should always take responsibility
  2. An LLM automation assistant acts as an assistant, not as a replacement
  3. The SE needs to write and understand the code. It won't work if an LLM takes over
  4. A flexible process is needed to ensure that I can easily use LLM automation. The LLM can ask, can provide advice, but isn't allowed to write code into the project. And I need access to it whenever I need to.

What does that really mean?

For starters, the SE writes ideas, explorations, specs, plans and code. At any time during these tasks the SE should have easy access to an LLM to review, to ask questions, to act as a rubber duck, or to get him or her a coffee, whatever suits you best. The goal is not to get things done quickly. The goal is to get things done as best as the SE can accomplish.

The most important aspect of this is that you need to ensure the LLM doesn't get ahead of you. Or that it tries to get into action when you do not want it to. It should ask questions and only provide a direction or answers if there are no ways to explore a problem further.

An assistent then

To do this I've written a small addition to my editor that allows me to discuss issues with an LLM (Claude in this case). It takes the form of an assistant for exploration, specs, planning, code and review processes. It won't write code but will respond to questions. The editor puts a shell around Claude and forces it to analyze and offer me questions when I ask for it.

Example in practice: a "faster" quicksort implementation

To test this idea, I decided to implement quicksort in Clojure. There exist many implementations already, so it is a no brainer for an LLM to find working code and be done with it. The point is that I need to do it, I need to understand it, and I need to make decisions on how to accomplish it in the best possible way (that I am capable off). To be sure, I am not a Clojure or sorting expert. I can write code, understand algorithms, but I usually work on the client side of things.

After setting up a basic project for Clojure using Neil, I set up my editor to use an nrepl and I am ready to write some code.

Before I do that, I first explore the idea a little. What is it that I want to try to do? I end up with an idea to write a Clojure based version of quicksort and comparing it to the default (and optimized) sort function in Clojure. Ideally, I would love it if the solution works and is not too slow compared to sort.

From there I need a spec, and there I need to add a lot more detail to the idea, to make sure I can implement and verify that the implementation is what I expected it to be. I won't bother here to explain exactly how the spec is written, but during this phase it is very helpful to have an LLM review what you write, offer insights into areas you may need to be more specific and annoy you by asking what you actually mean by saying the implementation should not be too slow compared to sort. I end up writing down that it can be 3 times slower (a random choice really), measured using Criterium and a sample of 10,000 random numbers in a vector.

How the assistant helps there is perhaps for another blog post.

Writing the code

I know the basics of quicksort. You take a list (vector) of numbers, choose a pivot point (for example the number that is in the middle of the list), and then split the vector into 3 parts, a list with numbers smaller, equal or larger than the pivot. And then call the same algorithm on these sub-lists.

Group-by

The simplest form I can think of initially to generate these 3 parts is to use group-by. I think the pivot can really be chosen anywhere in the list, but to keep the recursive work done on the left and right side balanced I will select the number that is approximately in the middle of the list. Sorting is done by a comparator, but initially I'll just pass #(< %1 %2).

(defn q-sort "Quicksort algorithm based on Clojure functions. Takes immutable sequences a comparator cmp and a collection coll" [cmp coll] (if (seq coll) (let [nth-ind (int (/ (count coll) 2)) pivot (when (seq coll) (nth coll nth-ind nil))] (let [split-coll (group-by (fn [x] (cond (cmp x pivot) :smaller (cmp pivot x) :larger :else :equal)) coll)] (concat (q-sort cmp (:smaller split-coll)) (:equal split-coll) ;duplicates (q-sort cmp (:larger split-coll))))) []))

By splitting the data, and concatenating the recursive results, we will eventually sort the list of numbers.

I also need a function to generate a random list of numbers and a way to see if the quicksort works as expected.

(defn rand-seq "Generate a seq of n random numbers between 0 and n-1" [n] (take n (repeatedly #(rand-int n))))

And a small function to collect some initial data.

(defn run-sort-experiment "Run the different sorting implementation on coll and get the results" ([coll] (run-sort-experiment #(< %1 %2) coll)) ([cmp coll] (let [quick-s (time (q-sort cmp coll)) normal-s (time (sort cmp coll)) same (= quick-s normal-s)] {:data coll :quick-s quick-s :normal-s normal-s :same same})))

Running the experiment a few times shows that the implementation is quite a bit slower than the native sort function Clojure provides.

"Elapsed time: 0.1225 msecs" "Elapsed time: 0.022333 msecs" {:data (3 1 8 3 7 6 2 9 3 5), :quick-s (1 2 3 3 3 5 6 7 8 9), :normal-s (1 2 3 3 3 5 6 7 8 9), :same true}

Time is a nice utility function but not the best way to measure performance. We'll fix that later. First thing to note is that the code takes some effort to find the element in the center of the list. If we ensure the input list is a vector, then the lookups will be O(n).

We can wrap q-sort in a function where we transform the input to a vector.

(defn quicksort "Map a seq to a vec and call q-sort on it" [cmp coll] (let [coll-v (into [] coll)] (if cmp (time (q-sort cmp coll-v)) (time (q-sort #(< %1 %2) coll-v))))) "Elapsed time: 0.043917 msecs" "Elapsed time: 0.013875 msecs" {:data (1 9 7 4 0 6 7 8 3 8), :quick-s (0 1 3 4 6 7 7 8 8 9), :normal-s (0 1 3 4 6 7 7 8 8 9), :same true}

That seems to improve quite a bit, but in fairness, sort does a similar transformation inside the time call, so we should really place the time function around quicksort. That will make the implementation slower.

"Elapsed time: 0.104459 msecs" "Elapsed time: 0.019583 msecs" {:data (0 7 1 9 7 1 9 6 8 2), :quick-s (0 1 1 2 6 7 7 8 9 9), :normal-s (0 1 1 2 6 7 7 8 9 9), :same true}

Worse, when we try a much larger set, say 100,000 numbers, the speed differences become much larger (10x).

"Elapsed time: 267.2955 msecs" "Elapsed time: 26.187875 msecs" {:data (10234 65395 59633 15317 32687 15360 40784

That won't do. It seems there is a lot of overhead in the initial approach. I think using group-by is probably not super-efficient. It is time to ask for some advice.

> I want to speed up q-sort. What can I do? Before changing anything, find out where the time goes and how far you are from the spec's bar of within 2× of `sort`. Some things to consider: - **Is the measurement trustworthy?** `time` on a single run includes JIT warm-up, so early numbers can mislead. The spec's Acceptance criteria call for criterium for this reason. - **How often is the comparator called?** With a boolean predicate, each element may cost two calls per level. A three-way comparator (negative, zero or positive, like `compare`) gives the same answer in one call. The spec also asks for `compare` as the default, not `<`. - **What does each level allocate?** Your grouping builds a fresh map of new collections at every level. Ask how much of the work is sorting and how much is building intermediate structures. - **What does the result cost to walk?** Lazy concatenations nested level by level each add a layer that every element passes through when the result is consumed. - **Where does the recursion stop?** The spec says zero- or one-element inputs come back as they are. Your code still partitions single elements and recurses into two empty parts. That's a lot of calls near the leaves. The principle: measure, then change one thing at a time and measure again. The experiment below compares how often the comparator is called by your version and by `sort` on the same input.

So, instead of getting the code to fix it, the assistant gives me some questions and hints regarding things that I might need to consider. There is a lot to digest, but I can see that I'm trying to create 3 groups with a < while a comparator already offers that because it returns one of 3 values.

The group-by feels like a slow solution. Instead of a map it would be more efficient if I can use vectors instead. And finally, I feel the code to find the middle item in the list is a bit clumsy, especially with the conversion to int. Searching a bit in the Clojure functions gives me quot which makes the code slightly more readable.

The updated version looks like this:

(defn q-sort "Quicksort algorithm based on Clojure functions. Takes immutable sequences a comparator cmp and a collection coll" [cmp coll] (if (seq coll) (let [pivot (nth coll (quot (count coll) 2) nil) split-coll (group-by (fn [x] (let [res (cmp x pivot)] (cond (neg? res) :smaller (zero? res) :equal (pos? res) :larger))) coll)] (concat (q-sort cmp (:smaller split-coll)) (:equal split-coll) ;duplicates (q-sort cmp (:larger split-coll)))) '()))

This is not much faster, but we still need to get rid of the group-by. What we need is a list that holds these three groups, something like [[smaller] [equal] [larger]]. The recursion can then be done using vectors.

Reduce

My first thought was to replace group-by with something that iterates over the vector and builds the list of lists. If we get that right, we only need to iterate once. It turns out we can use reduce for that.

(reduce (fn [[smaller equal larger] x] (let [res (cmp x pivot)] (condp = res -1 [(conj smaller x) equal larger] 1 [smaller equal (conj larger x)] 0 [smaller (conj equal x) larger]))) [[] [] []] coll)

Which turns the function into:

(defn q-sort "Quicksort algorithm based on Clojure functions. Takes immutable sequences a comparator cmp and a collection coll" [cmp coll] (if (seq coll) (let [pivot (nth coll (quot (count coll) 2) nil) split-coll (reduce (fn [[smaller equal larger] x] (let [res (cmp x pivot)] (condp = res -1 [(conj smaller x) equal larger] 1 [smaller equal (conj larger x)] 0 [smaller (conj equal x) larger]))) [[] [] []] coll)] (concat (q-sort cmp (nth split-coll 0)) (nth split-coll 1) ;duplicates (q-sort cmp (nth split-coll 2)))) '()))

It looks quicker, at least on a small data set.

"Elapsed time: 0.038666 msecs" "Elapsed time: 0.009875 msecs" {:data (3 6 9 0 6 8 4 0 0 1), :quick-s (0 0 0 1 3 4 6 6 8 9), :normal-s (0 0 0 1 3 4 6 6 8 9), :same true}

On a dataset of 100,000 items, it is still about 9 times slower. Time to ask for some advice again:

>How can I further speed up the q-sort function For speed, some things to weigh: - **Allocation per element:** each step of your fold builds a new triple and conjs onto a persistent collection. The three parts are private to this call until it returns. Could they be built mutably inside the function and handed back as immutable values? - **The leaves:** a one-element part still gets a full split and two recursive calls on empty parts. Most calls in a quicksort happen near the leaves. The spec says zero or one element comes back as it is. - **The result:** each level wraps its parts in a lazy concatenation. How much does walking those layers cost compared with the splitting itself? - **The measurement:** a single `time` run includes JIT warm-up. Warm up several runs, or use criterium as the spec asks, before trusting a ratio. > What can I do about the persistent collection The principle: a value only has to be immutable where someone else can see it. Your three parts are private to one call until it returns, so mutating them while you build them can't leak, as long as you hand back immutable values. Clojure supports exactly this: its vectors and maps have a mutable-while-building form, which you switch into at the start of a local loop and back out of at the end. The clojure.org reference has a section on it.

Interesting! There is a solution that can be found at clojure.org, not sure what that is all about. Googling Clojure mutable while building form immediately points me to transient data structures. I had never used them before, and I need to read about it a bit to understand what they are.

Transients

Turns out that transient data structures allow you to manipulate data locally without them re-creating intermediate nodes. Clojure data is immutable, and under normal circumstances this means that altering data means copying old data first. With transient data this is done differently.

Data manipulation is done without copying the data first, instead the nodes are reused if possible. This is especially convenient when using heavy loops, as the copying of data is a relative expensive operation. Immutability still exists but there are restrictions. for example, you cannot share intermediate transient values across threads or keep references on them. You get your immutable data structure back by calling persistent! which converts the transient data back to persistent data.

Sounds like this is very useful for the quicksort implementation so far. After a bit of experimenting (meaning I write code, evaluate, see it crash in the repl, and repeat) the code now looks like this:

(defn q-sort "Quicksort algorithm based on Clojure functions. Takes a comparator cmp and a collection coll." [cmp coll] (if (seq coll) (let [pivot (nth coll (quot (count coll) 2) nil) [smaller similar larger] (reduce (fn [[smaller similar larger] x] (let [res (cmp x pivot)] (cond (neg? res) [(conj! smaller x) similar larger] (pos? res) [smaller similar (conj! larger x)] :else [smaller (conj! similar x) larger]))) [(transient []) (transient []) (transient [])] coll)] (concat (q-sort cmp (persistent! smaller)) (persistent! similar) ;duplicates (q-sort cmp (persistent! larger)))) []))

This implementation is faster. On 100,000 numbers the results look like this:

"Elapsed time: 115.497084 msecs" "Elapsed time: 31.410917 msecs" {:data (80822 45820 5684 87574 23509 36848 75874

The next thing I can think of is to look at concat. It is a very useful and easy to read function, but I am not certain that it is quick. Perhaps we can replace the concat and use transients for that too. I can try using reduce again and set it up to use transients as well.

I want to somehow build the three lists with reduce and then add the recursive results to that. The solution is like the one used above. We can use reduce in combination with conj! and a transient [] to build the data structures. The only thing to think about is how to create the list of lists that we are building.

As->

After trying some experiments using the -> macro I am settling on as->. It lets me bind an expression to a name and use that.

(persistent! (as-> (transient []) acc (reduce conj! acc (q-sort cmp (persistent! smaller))) (reduce conj! acc (persistent! similar)) ; duplicates (reduce conj! acc (q-sort cmp (persistent! larger)))))

As you can see, I need to convert transient data structures to persistent ones here and there, but since that is an O(1) operation, that is relatively cheap.

The final code looks like this:

(defn q-sort "Quicksort algorithm based on Clojure functions. Takes a comparator cmp and a collection coll." [cmp coll] (if (seq coll) (let [pivot (nth coll (quot (count coll) 2) nil) [smaller similar larger] (reduce (fn [[smaller similar larger] x] (let [res (cmp x pivot)] (cond (neg? res) [(conj! smaller x) similar larger] (pos? res) [smaller similar (conj! larger x)] :else [smaller (conj! similar x) larger]))) [(transient []) (transient []) (transient [])] coll)] (persistent! (as-> (transient []) acc (reduce conj! acc (q-sort cmp (persistent! smaller))) (reduce conj! acc (persistent! similar)) ; duplicates (reduce conj! acc (q-sort cmp (persistent! larger)))))) []))

And now it is time to do some more accurate timing to see if this implementation holds up. To do that we can use Criterium a benchmarking library for Clojure.

Adding Criterium

I need to add the library to the deps.edn file of the project and then include it in the file.

{:paths ["src"] :deps {criterium/criterium {:mvn/version "0.4.6"}} :aliases {:neil {:project {:name quicksort/quicksort}} :nrepl {:extra-deps {nrepl/nrepl {:mvn/version "1.8.0"} cider/cider-nrepl {:mvn/version "0.64.1"} refactor-nrepl/refactor-nrepl {:mvn/version "3.16.0"}} :main-opts ["-m" "nrepl.cmdline" "--interactive" "--color" "--middleware" "[cider.nrepl/cider-middleware,refactor-nrepl.middleware/wrap-refactor]"]}}} (ns quicksort.quicksort "Writes 2 different quicksort implementations, a random input function and a test against the clojure sort function" (:require [criterium.core :as crit]))

To set it up is relatively easy, we can add a few lines to the source file and evaluate them.

(def test-data (vec (repeatedly 10000 #(rand-int 100000)))) (crit/quick-bench (doall (quicksort compare test-data))) (crit/quick-bench (sort compare test-data))

After running it with the quicksort implementation and the default sort function for Clojure we see the following results (after running the experiments a few times in a row):

The quicksort implementation gives the following result:

Evaluation count : 138 in 6 samples of 23 calls. Execution time mean : 4,791885 ms Execution time std-deviation : 246,347455 µs Execution time lower quantile : 4,533595 ms ( 2,5%) Execution time upper quantile : 5,070039 ms (97,5%) Overhead used : 1,261889 ns

The default sort function gives the following results:

Evaluation count : 504 in 6 samples of 84 calls. Execution time mean : 1,192351 ms Execution time std-deviation : 17,291686 µs Execution time lower quantile : 1,173747 ms ( 2,5%) Execution time upper quantile : 1,217670 ms (97,5%) Overhead used : 1,261889 ns Found 1 outliers in 6 samples (16,6667 %)

Final results

MetricBuilt-in sort(doall (quicksort ...))ComparisonMean execution time1.192 ms (1,192.35 µs)4.792 ms (4,791.89 µs)quicksort takes ~3.60 ms longer (~4.0x slower)Previous mean1.218 ms11.938 mssort is ~2.1% faster; quicksort is ~2.5x fasterStandard deviation17.29 µs246.35 µsquicksort variation is ~14.2x larger95% quantile range1.174 ms – 1.218 ms (~44 µs span)4.534 ms – 5.070 ms (~536 µs span)quicksort span is ~12.2x widerEvaluations504 (6 samples × 84 calls)138 (6 samples × 23 calls)Criterium ran ~3.7x more calls for sortOutliers1 of 6 samples (16.7%)None reportedCleaner sample set for quicksort in this run

The quicksort implementation is now on average 4 times slower than the default sort of Clojure. I was hoping for a factor of 3 times slower, but this is not too bad, I think.

It makes sense, as the default sort function takes a different approach. It converts the data to a flat java data array and then swaps data inside the array, where the quicksort implementation uses recursion and persistent data structures to move data around.

There are still possibilities to further improve this code. Perhaps a good next step would be to look at recursion, or using java-based data structures. The point wasn't to build the fastest quicksort. I wanted to see if I could write an improved quicksort with some advice once I got stuck.

Conclusion

It is easy to get an LLM to write code for you. And it might (or might not) be better code than what you are capable of. The real issue is that when you try to outsource your brain, the LLM will deliver, but you do not know what. You have few means to figure out if it is what you asked for. Not only does it make merging code more difficult, but it literally dumbs you down, as you likely will have difficulty understanding what was built.

I tried something in between. I want to be responsible for the things I create, so that implies I must write the code myself. My knowledge and experience can get me to a certain level. I can ask a colleague to provide advice, look at open-source code, search stack overflow or other online sources. I can now also ask an LLM to ask me questions so that I can explore things I had not thought about or did not know about.

I've created a small assistant interface for that. It is embedded in my editor which also holds the code. A repl connection allows me to write code, experiment, and ask for help when needed. It offers help in several detail levels, from global to more detailed. It will only go into more detail if I tell it to. I've stayed with the global advice for now. It isn't ready yet, there are lots of little things to further improve. But it seems to work for what I wanted it to do.

I am not sure if this is the best way to move forward, but it feels promising. I'm still in control, learned new things, and ended up writing better code, and code I could understand, after just a few iterations.