Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best sorting algorithms when 'n' is very small?

In the critical path of my program, I need to sort an array (specifically, a C++ std::vector<int64_t>, using the gnu c++ standard libray). I am using the standard library provided sorting algorithm (std::sort), which in this case is introsort.

I was curious about how well this algorithm performs, and when doing some research on various sorting algorithms different standard and third party libraries use, almost all of them care about cases where 'n' tends to be the dominant factor.

In my specific case though, 'n' is going to be on the order of 2-20 elements. So the constant factors could actually be dominant. And things like cache effects might be very different when the entire array we are sorting fits into a couple of cache lines.

What are the best sorting algorithms for cases like this where the constant factors likely overwhelm the asymptotic factors? And do there exist any vetted C++ implementations of these algorithms?

like image 554
Chuu Avatar asked Sep 17 '25 20:09

Chuu


1 Answers

Introsort takes your concern into account, and switches to an insertion sort implementation for short sequences.

Since your STL already provides it, you should probably use that.

like image 56
Matt Timmermans Avatar answered Sep 20 '25 08:09

Matt Timmermans