Go will use pdqsort in next release
github.com
github.com
Changing std:sort at Google’s scale and beyond - https://news.ycombinator.com/item?id=31098822 - April 2022 (144 comments)
Whether you call that an "algorithmic improvement" or not is mostly semantics, it would not have been called such in the 80s but it would be today - what properties we consider part of "the algorithm" has also changed to meet hardware changes.
Even whether it's "parallelization" is somewhat semantics - if you change an algorithm to avoid a pipeline stall, is that designing it for parallelization? I guess not because it's single-threaded, but again someone in the 70s/80s might say yes because two things are happening at once.
The point of my comment is that not only are the sorting algorithms changing over time, but what we say constitutes "algorithmic" vs. "implementation" changes also changes over time, so it's really hard to say whether certain changes are "algorithmic" changes or not!
The fastest way to sort integers is a radix-256 increasing-significance radix sort, and that has been a well-known fact since the 1960's. In other words: a stable bytewise counting sort, sorting from least-significant byte to most-significant byte.
A comparison sort, no matter how clever, will not outperform a radix sort, except for very small arrays or very large (many byte) integers.
> I think it's fair to say that pdqsort (pattern-defeating quicksort) is overall the best unstable sort and timsort is overall the best stable sort in 2017, at least if you're implementing one for a standard library.
_hrfd called it 5 years ago.
Maybe not anymore?
Hi all, I'm the author of pdqsort. I recently held a talk at my institute on efficient in-memory sorting and the ideas in pdqsort, in case you're interested in hearing some of the theory behind it all: https://www.youtube.com/watch?v=jz-PBiWwNjc Next week I will hold another talk in the Dutch seminar on data systems design (https://dsdsd.da.cwi.nl/) on glidesort, a new stable sorting algorithm I've been working on. It is a combination of adaptive quicksort (like pdqsort, fully adaptive for many equal elements) and an adaptive mergesort (like timsort, fully adaptive for long pre-sorted runs). It is the first practical implementation of an algorithm I'm aware of that's fully adaptive for both. Like pdqsort it uses modern architecture aware branchless sorting, and it can use an arbitrary buffer size, becoming faster as you give it more memory (although if given a constant buffer size it will degrade to O(n (log n)^2) in theory, in practice for realistic workloads it's just a near-constant factor (c ~<= 3-5) slower).
The source code isn't publish-ready yet, I have to still do some extra correctness vetting and testing, and in particular exception-safety is still not yet fully implemented. This is important because I wrote it in Rust where we must always give back a valid initialized array, even if a comparison operator caused a panic. But I do have some performance numbers to quote, that won't significantly change.
For sorting 2^24 randomly shuffled distinct u32s using a buffer of 2^23 elements (n/2), glidesort beats Rust's stdlib slice::sort (which is a classic timsort also using a buffer of n/2) by a factor of 3.5 times. When stably sorting the same numbers comparing only their least significant 4 bits, it beats stdlib slice::sort by 12.5 times using 6.5 times fewer comparisons, both numbers on my Apple M1 Macbook. All of this is just using single-threaded code with a generic comparison function. No SIMD, no threads, no type-specific optimizations.
Finally, glidesort with a buffer size of >= n/2 is faster than pdqsort.
Do you make extensive use of `unsafe` Rust? What other features do you use? I ask this as my PhD thesis is building a deductive verifier for (safe) Rust, and I'm always looking out for interesting challenges.
If you would ever be interested in a collaboration proving your algorithm correct let me know :)
Yes. Glidesort moves data back and forth between partially initialized buffers a lot, so unsafe code is unavoidable. I also need to concatenate slices that are adjacent in memory, which is impossible to do with safe slices (due to pointer provenance). Mixing pointers/slices in general is just a bad idea, so for the most part I simply use pointers.
I use no other special (unstable) features, just pointers and ptr::copy(_nonoverlapping).
> If you would ever be interested in a collaboration proving your algorithm correct let me know :)
I might take you up on that, or at least ask you to take a look once I'm done polishing the code.
Ah, that's frustrating, my tool Creusot is meant for the verification of safe code, though I also worked on unsafe code verification as part of the RustHornBelt project (upcoming PLDI paper).
I'd still love to chat and see how far we can push verification, you can reach me via email at xldenis @ lri . fr
I just assumed Einstein-tier people had discovered all the optimal ways to do things by now.
Do you have a process for coming up with these improved algorithms, or does it just start from a passing thought in your mind?
And that's ignoring that "optimal" is a shifting target. What's optimal on a 1960s computer where RAM is as fast as registers may not be optimal on a modern CPU with instruction-level parallelism and RAM that's orders of magnitude slower than registers.
The worst part is that most people pursuing a computer science degree actually want to learn about software engineering, so most curricula nowadays disappoint both the people that want to become software engineers ("why do I have to learn about formal grammar automata") and those that want to become computational mathematicians ("why do I have to do a course on agile?").
But I can say that mathematics is an ancient "science" which has been studied by great scholars for millennia, but many of the things we take for granted today are relatively recent: modern set theory was introduced 150 years ago by Cantor and Dedekind, meaning things like Russel's Paradox [1], Gödel's Incompleteness Theorem [2] and the Peano Axioms [3] have all been discovered after that, despite being taught in many (university-level) introductory math courses today. Rings are also relatively young [4]. In comparison, imaginary numbers are about 500 years old.
1: https://brilliant.org/wiki/russells-paradox/
2: https://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_...
An easy way to reconcile this is to consider that everything is an engine (~ 'system that transforms energy'); and likewise that everything is a computer (~ a 'system that turns inputs to outputs'). Each field offers a different perspective, on different aspects of, the world :)
If anything I think he missed a key component which is that algorithmic improvement is actually only interesting in a few very specific places.
I think pdqsort actually shows this to be true - it uses added complexity to improve on things that really do fit in a few lines of pseudocode.
> An algorithm M is described that solves any well-defined problem p as quickly as the fastest algorithm computing a solution to p, save for a factor of 5 and low-order additive terms
Spoiler alert, the "algorithm M" is a brute-force search; the "low-order additive terms" in its time complexity come from brute-force searching for provably faster programs; if one is found, we restart with that. All the time spent searching for proofs is independent of the input size (e.g. it depends on "sorting", but not which particular list we've been given); hence it's technically just a constant 'warmup time'!
This is the answer to your question, almost everyone makes the same assumption you do.
There are a surprising number of problems in computer science that no one works on because everyone assumes that other clever people are. Relatedly, people assume the set of possible solutions has been exhaustively explored because there have been no incremental improvements in decades. Or people assume the scope of optimality of a well-known solution is much broader than it actually is.
The vast majority of people in software never test or revisit these assumptions. If you do test these assumptions, you will be surprised by how often you find low-hanging fruit.
Because it's a moving target. There isn't a fixed 'optimal' sorting algorithm.
We've had worst case O(n log n) sorting algorithms for decades, since at least the '50s, possibly the '40s. pdqsort isn't more 'optimal' in the algorithmic sense than merge sort is, they're both worst/expected O(n log n) algorithms.
If RAM is low-latency and your CPU isn't super scalar, heapsort is going to take less time than quicksort. With high-latency RAM and speculative executing CPUs, quicksort is going to take less time than heapsort. So every few hardware generations we need to sit down and benchmark everything.
pdqsort is based on the principal that the real world is different than the academic world. There are no frictionless spherical cows in a vacuum. In academic research, we assume that the data has been contrived to break your algorithm, or it's randomly distributed. In the real world, data is almost never randomly distributed. A lot of data that gets plugged into your standard library of choice's sorting algorithm is already sorted. Or is sorted in reversed. Or is sorted with one random element plopped onto the end. Or is sorted with one element randomly in the middle that's out of place. pdqsort is designed to account for that.
https://github.com/golang/go/blob/master/src/sort/sort.go#L4...
[citation needed]
This is the wrong wording, IE had a decently enough installed/captive user base. It was never particularly stable.
Otherwise the only way to have a non-stable sort function that currently happens-to-be stable would have to include a randomized shuffle afterwards to ensure no one goes around depending on it…
It would be equivalent to assuming the golang ABI was stable because it survived unmodified for a couple versions, despite it being explicitly not. And then freezing the ABI to maintain a guarantee it explicitly didn’t want to maintain.
On a similar note, Im sure there was a suggestion to artificially make the previous golang sort function unstable so that users wouldn't come to rely on stable behaviour where it wasn't guaranteed. I quite like the idea, start the fight against hyrum's law!
In theory, yes. In practice, if a OS or library update uncovers bugs in many programs, that update won’t get favorable reviews.
That’s the reason behind Linux’s “we do not break userspace!” rule (https://linuxreviews.org/WE_DO_NOT_BREAK_USERSPACE), and also why Microsoft Windows has layer upon layer of APIs, a copy of the Windows 95 memory manager (https://mcpmag.com/articles/2010/07/27/trip-down-memory-lane...), why large databases support character sets that probably haven’t been used anywhere since before many HN readers were born (https://docs.oracle.com/goldengate/1212/gg-winux/GWUAD/wu_ch...), etc.
(Apple has a totally different viewpoint on this. That’s one reason it never really got into businesses for a long time)
Block real innovation like what?
> Granted, Desktop Linux doesn't need another Python 2 -> 3 or X.org -> Wayland deathmarch...
That's all userspace? Userspace doesn't care it breaks. That's why userspace sucks. You need to keep compatibility if you want to have a stable base to build something. That's why we have (sometimes silly) standards like SUS or POSIX.
"we do not break userspace" at least garantees that you need to fix only the userspace, and not the whole thing all the time.
Significant changes in the kernel already often need years to land because of the multitude of configurations and interfaces that have to be supported. And even longer to deprecate and remove. Not necessarily a bad thing, just the price of success.
Large-scale breakages like the Wayland transition affect the whole Desktop Linux ecosystem, and are just an example of what mayhem fundamental changes can cause.
There's a debate/lesson in here about when implementations should change to actually take up all the space claimed by the spec.
As a result most people will go "Oh, I guess I should actually test the outcome I care about" (good) or "Oh, testing is hard, I'll skip it" (bad, but at least not a problem for the team maintaining the standard library). Very few will say to themselves "I bet I can defeat the randomisation somehow with a different incorrect test design" because humans are lazy.
There aren't a lot of places where stability matters, where it does the programmer should hopefully know and not have relied on an undefined behaviour… The most likely impact, I think, will be in UIs where the difference won't really matter but could be quite noticeable.
Do note though that "unstable" can mean two different things. A single threaded sort will produce the same result for the same input, and many parallels sorts have this property too due to the way they coordinate the threads and collate their results, so the output order of equal items is arbitrary but not random. Some parallel sorts do order items with the same sort key more randomly though due to being sensitive to timing differences caused by uncontrolled factors (the OS's scheduler and other things it is dealing with, differing IO delays if the sort is not in-memory, different numbers of threads if comparing run results with those done on other processor architectures, …). IIRC pdqsort is the former if those two types of unstable.
I'm just noting that users are necessarily flawed, and moving from "stable but not guaranteed to be" to "actually unstable" will be a breaking change for some real world codebases.
Seems really odd that the same team would have used a stable sort and just documented as “not guaranteed to be stable”.
The reason is that a hash table with a fixed hash function may be used for denial of service attacks. If an attacker knows how a hash map maps keys and can control the keys being inserted, they can insert thousands of keys that all map to the same hash, effectively turning the hash map into a list or vector that has to be searched linearly (on both lookups and insertions)
And that’s a real problem. https://lwn.net/Articles/474912/ says:
“That's where web frameworks come into play. Those frameworks helpfully collect up all of the POST form data that gets sent to a particular web page into a dictionary that gets handed off to the application for processing. The amount of data that the frameworks will allow is typically rather large (e.g. 1MB), so an attacker can create tens of thousands of form entries in a single HTTP request. Because they all collide, those entries can take tens of seconds to a few minutes to process on an i7 core according to the advisory [PDF] released by Wälde and Klink.”
If you manage to insert 10,000 keys with identical hashes, that’s about 10,000²/2 key comparisons.
They absolutely are.
> The reason is that a hash table with a fixed hash function may be used for denial of service attacks. If an attacker knows how a hash map maps keys and can control the keys being inserted, they can insert thousands of keys that all map to the same hash, effectively turning the hash map into a list or vector that has to be searched linearly (on both lookups and insertions)
That has nothing to do with what I'm talking about.
Independent from hash randomisation, Go will randomise the iteration of hashmaps, such that iterating the same hashmap twice, within the same process, without having modified it in any way, will yield different results. Currently this is done by offsetting the starting point of the iteration by a random amount.
For some reason they dropped this explicit mention when https://go.dev/blog/go-maps-in-action was moved over to https://go.dev/blog/maps, but it used to be there:
> Since the release of Go 1.0, the runtime has randomized map iteration order. Programmers had begun to rely on the stable iteration order of early versions of Go, which varied between implementations, leading to portability bugs.
You can trivially observe this behaviour by just iterating the same map multiple times. With mere hash randomisation, even if hash randomisation was done on a per-map basis by iterating the same map you'd observe the same order, but in Go you don't: https://go.dev/play/p/3HZBv2WHKcT
As you can see the items are always in the same relative order, but the starting point of the iteration varies.
You can also see this in the initialisation of the map iterator, it's even labelled with a nice little comment: https://github.com/golang/go/blob/master/src/runtime/map.go#...
And Hyrum's law in general: https://www.hyrumslaw.com/
Then I had a larger input (like 100k elements) and wondered, why does it take a few minutes to print the output, when it calculated the output in a second? Well, it was the merge sort being called after the calculation completed to print it sorted. A double fail, because the calculation already produced sorted output in this case.
Now I sort a list of indices with quick sort
Direct link to the GitHub home of pdqsort (in C++), which has some performance comparisons: https://github.com/orlp/pdqsort
Overall, I think the Go standard library does pretty good here, and yet it could still do better, and it’s definitely nice to see it improve.
That's so interesting- I think I have the opposite response. I figure unless I'm doing a very specific case that doesn't fit well with the stdlib sort (for some specific reason), It's probably good enough. Those language folks usually know their stuff, who am I to try something else?
My comment also had a more dismissive tone than I intended.
It's interesting to think that sorting has a maximum "total complexity", distributed across the whole input space. And this hybrid algorithm kind of shapes that distribution, squeezing efficiency out of one part of the space, and into another, more practically meaningful part.
(Just joking but some interviews indeed feel that way)
The candidate does not get paid to solve the interview test, but it could be seen as a collaborative effort on both the company and the candidate, since both put time and engineering resource in it.
If it can be regarded as an intellectual property, does that mean that the company would be infringing on the candidate’s right?
If you do hire them then I guess it becomes fine, but otherwise definitely immoral.
The problem is that we’re fleshy meatbags and easily influenced. It’s possible we internalise answers to interview questions and then “spontaneously” come up with them later, without _knowingly_ stealing the idea.
This happens sometimes in comedy, and the comedian apologises. You can usually tell the difference in comedy between plagiarism and accidental theft because the joke is delivered much differently but has the same core. It would be harder with interview answers.
Not that anything will stop companies from doing this, and not that I think it ever really happens, but for it to be morally OK I think you’d have to both get their permission and compensate them fairly.
Before I work for you, my ideas are mine even if I write them on your whiteboard.
Why would I trust the answer more than the person?
Why wouldn't you? The truth of statements is not a function of the people making them (though of course that can often be a strong indicator of truth).
Or, put differently: if I’m the candidate and they end up “stealing” my solution, that’s a small price to pay to avoid working in what is likely a terrible environment.
However some whiteboard scribbles are not the same as working code, so it is likely easy to make an implementation that does not infringe in most cases. Not that it really matters because it's highly unlikely that anyone is going to sue over it.
To ask interviewees a question about an actual issue you have and see what solutions they come up with is clever. You get more input for free and you may find someone you want to hire.
I don't see a problem as long as you are really looking to hire someone and not advertising fake job openings.
I've had candidates use useful Python libraries that I didn't know about in tech tests before, but that's pretty much the extent to which I've learned anything helpful when recruiting
[0] I mean, this has happened for real: Bram Cohen (BitTorrent co-inventor) / brew's (package manager for macOS) co-developer couldn't get past Google interviews: https://news.ycombinator.com/item?id=9695102
https://en.wikipedia.org/wiki/George_Dantzig
Does anybody have more examples?
Dantzig, George B. “On the Non-Existence of Tests of ‘Student’s’ Hypothesis Having Power Functions Independent of Sigma.” Annals of Mathematical Statistics. No. 11; 1940 (pp. 186-192).
Dantzig, George B. and Abraham Wald. “On the Fundamental Lemma of Neyman and Pearson.” Annals of Mathematical Statistics. No. 22; 1951 (pp. 87-93).
[1] https://www.snopes.com/fact-check/the-unsolvable-math-proble...
(The algorithm boils down to the observation that (Xb + Y)(Zb + W) = XZ b^2 + [(X + Y)(Z + W) - XZ - YW] b + YW, for a total of three unique base-b products, plus what is nowadays a routine exercise to see that calculating these products recursively in base b/2 yields complexity n ^ log_2 3.)
> When George Dantzig brought von Neumann an unsolved problem in linear programming "as I would to an ordinary mortal", on which there had been no published literature, he was astonished when von Neumann said "Oh, that!", before offhandedly giving a lecture of over an hour, explaining how to solve the problem using the hitherto unconceived theory of duality.
> George Pólya, whose lectures at ETH Zürich von Neumann attended as a student, said "Johnny was the only student I was ever afraid of. If in the course of a lecture I stated an unsolved problem, the chances were he'd come to me at the end of the lecture with the complete solution scribbled on a slip of paper."
> https://en.wikipedia.org/wiki/John_von_Neumann#Cognitive_abi...
In fact they could probably have done this with a traditional Go interface if they weren't worried about missed optimizations.