Smoothsort in Zig

Smoothsort is a sorting algorithm with:

  • No recursion
  • O(1) memory
  • In place
  • Adaptive (O(N) for near sorted arrays)
  • O(NlogN) worse case

It’s the best sorting algorithm I found when you don’t want to allocate memory, you don’t want recursion, but you can expect your input to be relatively sorted, meaning that heapsort doing guaranteed O(NlogN) is not desirable. It was developed by dijkstra for that very reason.

The algorithm is also used in musl libc:

I have provided 2 implementations, an optimized one and one that I tried to make very readable. You should be able to understand the readable one if you do a small amount of research on the algorithm. If people are interested in it, I could do a tutorial because I didn’t find much in terms of good learning resources when I was implementing it.

The optimized one, I started calling assSort (assumption smoothsort) because I made some changes in the core logic of the algorithm to boost performance. The one I am sharing with you (assSort7) is about 20% slower than std heapsort on a random array in the benchmarks I ran. I still have some optimizations I want to try on it.

6 Likes