33 comments

  • ssivark3 hours ago
    Daniel Lemire&#x27;s points about low-level hardware optimization notwithstanding, it&#x27;s worth pointing out that binary search (or low-level implementation variants) is the best only if you know <i>nothing</i> about the data beyond the fact that it is sorted &#x2F; monotonic.<p>If you have priors about the data distribution, then it&#x27;s possible to design algorithms which use that extra information to perform MUCH better. eg: a human searching a physical paper dictionary can zoom into the right bunch of pages faster than pure idealized binary search; it&#x27;s a separate matter it&#x27;s hard for humans to continue binary search till the very end and we might default to scanning linearly for the last few iterations (cognitive convenience &#x2F; affordances of human wetware &#x2F; etc).<p>In mathematical language, searching a sorted list is basically <i>inverting</i> a monotonic function, by using a closed-loop control algorithm. Often, we could very well construct a suitable cost function and use gradient descent or its accelerated cousins.<p>More generally, the best bet to solving a problem more efficiently is always to use more information about the specific problem you want to solve, instead of pulling up the solution for an overly abstract representations. That can offer scalable orders of magnitude speedup compared to constant factor speedups from just using hardware better.
    • rixed2 hours ago
      &gt; it&#x27;s worth pointing out that binary search (or low-level implementation variants) is the best only if you know nothing about the data beyond the fact that it is sorted &#x2F; monotonic<p>Also if you do not learn anything about the data while performing the binary search, no? Like, if you are constantly below the estimate, you could gess that the distribution is biases toward large values and adjust your guess based on this prediction.
      • Nevermark30 minutes ago
        For a list of sorted values with no other knowledge, the binary search is optimal. Provably, it is simple information theory on binary information.<p>You can do better if the list is stable by reusing information.<p>But gathering that information during searches is going to require great complexity to leverage, as searches are an irregular information gathering scheme.<p>So create RAM for speedup optimizations up front.<p>1) Create a table that maps the first 8 bits to upper and lower indexes in the list. Then binary search over the last 8 bits. That reduces the search time in half.<p>2) Go all the way, and create an array of 32,768 indexes, with all 1&#x27;s for misses. Either way, search returns O(1).<p>Stable lists allow for sliding parametric trade offs between RAM-lookup vs. binary search. From full lookup, to full binary.
      • molf2 hours ago
        It&#x27;s not possible to learn anything about other elements when performing binary search, _except_ the only thing there is to learn: if the target is before or after the recently compared element.<p>If we would guess that there is a bias in the distribution based on recently seen elements, the guess is at least as likely to be wrong as it is to be right. And if we guess incorrectly, in the worst case, the algorithm degrades to a linear scan.<p>Unless we have prior knowledge. For example: if there is a particular distribution, or if we know we&#x27;re dealing with integers without any repetition (i.e. each element is strictly greater than the previous one), etc.
        • kryptiskt1 hour ago
          &gt; It&#x27;s not possible to learn anything about other elements when performing binary search, _except_ the only thing there is to learn: if the target is before or after the recently compared element.<p>You have another piece of information, you don&#x27;t only know if the element was before or after the compared element. You can also know the delta between what you looked at and what you&#x27;re looking for. And you also have the delta from the previous item you looked at.
          • wtallis1 hour ago
            And you always start off knowing the total length of the array, and the width of the datatype.<p>Actually deciding what to do with that information without incurring a bunch more cache misses in the process may be tricky.
            • xenadu0233 minutes ago
              Is the disconnect here that in many datasets there is some implicit distribution? For example if we are searching for english words we can assume that the number of words or sentences starting with &quot;Q&quot; or &quot;Z&quot; is very small while the ones starting with &quot;T&quot; are many. Or if the first three lookups in a binary search all start with &quot;T&quot; we are probably being asked to search just the &quot;T&quot; section of a dictionary.<p>Depending on the problem space such assumptions can prove right enough to be worth using despite sometimes being wrong. Of course if you&#x27;ve got the compute to throw at it (and the problem is large) take the Contact approach: why do one when you can do two in parallel for twice the price (cycles)?
    • hinkley2 hours ago
      I swear I read an article about treaps but instead of being used to balance the tree, they used the weights to Huffman encode the search depth to reduce the average access time for heterogenous fetch frequencies.<p>I did not bookmark it and about twice a year I go searching for it again. Some say he’s still searching to this day.
      • mvelbaum2 hours ago
        <a href="https:&#x2F;&#x2F;arxiv.org&#x2F;abs&#x2F;2206.12110" rel="nofollow">https:&#x2F;&#x2F;arxiv.org&#x2F;abs&#x2F;2206.12110</a> ?
    • painted-now2 hours ago
      &gt; In mathematical language, searching a sorted list is basically inverting a monotonic function, by using a closed-loop control algorithm.<p>Never thought about it this way. Brilliant!
    • mycall3 hours ago
      Furthermore, with the vast and immediate knowledge that LLMs have, we could see a proliferation of domain-specific sorting algorithms designed for all types of purposes.
    • tantalor3 hours ago
      &gt; use that extra information to perform MUCH better<p>Do you mean using a better estimator for the median value? Or something else?
    • locknitpicker3 hours ago
      &gt; If you have priors about the data distribution, then it&#x27;s possible to design algorithms which use that extra information to perform MUCH better.<p>You don&#x27;t even need priors. See interpolation search, where knowing the position and value of two elements in a sorted list already allows the search to make an educated guess about where the element it&#x27;s searching for is by estimating the likely place it would be by interpolating the elements.
      • rv64imafdc3 hours ago
        &gt; knowing the position and value of two elements in a sorted list<p>That&#x27;s a prior about the distribution, if a relatively weak one (in some sense, at least).
        • esafak1 hour ago
          <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Empirical_Bayes_method" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Empirical_Bayes_method</a>
      • darknoon2 hours ago
        This relies on knowledge of the distribution, just querying in the middle of A = [1, 2, 4, 8, 16, ..., 2^(n-1)] is slower than binary search
  • drkrab1 hour ago
    Since the cpu always accesses a full cache line (64 bytes) at a time, you might as well search the entire cache line (it’s practically free once the data is on-cpu). So I’d like to try a ‘binary’ search that tests all the values in the ‘middle cache line’ and then chooses to go left or right if none match. You can do the cache line search as a single 512bit simd instruction. A cache line is 64 bytes (or 32 16-bit integers); such a search might well be almost 32 times faster than simple binary search; at least it’ll do 32x less memory accesses, which will dominate in most realistic programs.
    • nly1 hour ago
      Searching the upper cache lines in your binary search tree (sorted vector) for your target is unlikely to yield results. Instead you want to use the extra data in the line to shorten the search, which leads you to a B-Tree or B+tree.<p>For 4 byte keys and 4 byte child pointers (or indexes in to an array) your inner nodes would have 7 keys, 8 child pointers and 1 next pointer, completely filling a 64 byte cache-line and your tree depth for 1 million entries would go down from ~20 to ~7, the top few levels of which are likely to remain cache resident.<p>With some thought, it&#x27;s possible to use SIMD on B-tree nodes to speed up the search within the node, but it&#x27;s all very data dependent.
  • lalitmaganti3 hours ago
    I also wrote recently [1] about Exponential Search [2] which is another algorithm if you need to repeatedly binary search in an array where the elements you&#x27;re searching are themselves are sorted. It allowed for an 8x speedup in our workload!<p>[1] <a href="https:&#x2F;&#x2F;lalitm.com&#x2F;post&#x2F;exponential-search&#x2F;" rel="nofollow">https:&#x2F;&#x2F;lalitm.com&#x2F;post&#x2F;exponential-search&#x2F;</a> [2] <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Exponential_search" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Exponential_search</a>
    • 10000truths2 hours ago
      Exponential search is useful when you&#x27;re querying a REST API that addresses resources with sequential IDs, and need the last ID, but there&#x27;s no dedicated endpoint for it:<p><pre><code> HEAD &#x2F;users&#x2F;1 -&gt; 200 OK HEAD &#x2F;users&#x2F;2 -&gt; 200 OK HEAD &#x2F;users&#x2F;4 -&gt; 200 OK ... HEAD &#x2F;users&#x2F;2048 -&gt; 200 OK HEAD &#x2F;users&#x2F;4096 -&gt; 404 Not Found </code></pre> And then a binary search between 2048 and 4096 to find the most recent user (and incidentally, the number of users). Great info to have if you&#x27;re researching competing SaaS companies.
  • drob5186 hours ago
    Isn&#x27;t &quot;quaternary&quot; just sort of unrolling the binary search loop by one level? I mean, to find the partition in which the item is located, you still do roughly the same rough number of comparisons. You&#x27;re just taking them 4 at a time, not 2 at a time. Seems like loop unrolling would give you the same.
    • nkurz5 hours ago
      It&#x27;s trickier than that. Modern processors are speculative, which means that they guess at the result for a comparison and keep going along one side of a branch as far as they can until they are told they guessed wrong or hit some internal limit. If they guessed wrong, they throw away the speculative work, take a penalty of a handful of cycles, and do the same thing again from a different starting point.<p>Essentially, this means that all loops are already unrolled from the processors point of view, minus a tiny bit of overhead for the loop itself that can often be ignored. Since in binary search the main cost is grabbing data from memory (or from cache in the &quot;warm cache&quot; examples) this means that the real game is how to get the processor to issue the requests for the data you will eventually need as far in advance as possible so you don&#x27;t have to wait as long for it to arrive.<p>The difference in algorithm for quad search (or anything higher than binary) is that instead of taking one side of each branch (and thus prefetching deeply in one direction) is that you prefetch all the possible cases but with less depth. This way you are guaranteed to have successfully issued the prefetch you will eventually need, and are spending slightly less of your bandwidth budget on data that will never be used in the actual execution path.<p>As others are pointing out, &quot;number of comparisons&quot; is almost useless metric when comparing search algorithms if your goal is predicting real world performance. The limiting factor is almost never the number of comparisons you can do. Instead, the potential for speedup depends on making maximal use of memory and cache bandwidth. So yes, you can view this as loop unrolling, but only if you consider how branching on modern processors works under the hood.
      • drob5185 hours ago
        Yea, I get that the actual comparison instruction itself is insignificant. It&#x27;s everything that goes along with it. Seems like quaternary is fetching more data, however.<p>For instance, if you have 8 elements, 01234567, and you&#x27;re looking for 1, with binary, you&#x27;d fetch 4, 2, and then 1. With quaternary, you&#x27;d fetch 2, 4, 6, then 1. Obviously, if you only have 8 elements, you&#x27;d just delegate to the SIMD instruction, but if this was a much larger array, you&#x27;d be doing more work.<p>I guess on a modern processor, eliminating the data dependency is worth it because the processor&#x27;s branch prediction and speculation only follows effectively a single path.<p>Would be interesting to see this at a machine cycle level on a real processor to understand exactly what is happening.
        • LoganDark4 hours ago
          It&#x27;s not about doing more or less work; it&#x27;s about doing the work <i>faster</i>. For instance, it&#x27;s relatively common to discover that some recomputation can be faster than caching or lookup tables. Similarly, fetching more from memory also can be faster if it means you make less roundtrips.
          • crdrost3 hours ago
            Well that&#x27;s where I thought this link was going to go before it went down the simd path... We have a way to beat binary search, it is called b-trees, it has the same basic insight that you can easily take 64 elements from your data set evenly spaced, compare against all of those rapidly, and instead of bifurcating your search space once, you do the same as six times, but because you store the 64 elements in an array in memory, they only take one array fetch and you get cache locality... But as you have more elements, you need to repeat this lookup table like three or four or five times, so it costs a bit of extra space, so what if we make it not cost space by just storing the data in these lookup tables...
    • wtallis6 hours ago
      Yes, this can be seen as unrolling the loop a bit. It improves performance not by significantly reducing the number of instructions or memory reads, but by relaxing the dependencies between operations so that it doesn&#x27;t have to be executed purely serially. You could also look at it as akin to speculatively executing both sides of the branch.
    • mayoff6 hours ago
      Quaternary search effectively performs <i>both</i> of the next loop iteration’s possible comparisons simultaneously with the current iteration’s comparison. This is a little more complex than simple loop unrolling.<p>Regardless, both kinds of search are O(log N) with different constants. The constants don’t matter so much in algorithms class but in the real world they can matter a lot.
    • loeg5 hours ago
      Sort of, yes, but you&#x27;re also removing a data dependency between the unrolled stages.
    • pfortuny5 hours ago
      It is because processors do not do what one might naively think they do.
  • taeric6 hours ago
    If you are talking smaller arrays, linear search with a sentinel value at the end is already tough to beat. The thing that sucks about that claim, is that &quot;smaller&quot; is such a nebulous qualifier that it is really hard to internalize.
    • rao-v6 hours ago
      This is simply not true - if you look at this article’s excellent benchmarking, linear search falls behind somewhere around 200-400 elements.<p>In general I love this article, it took what I’ve often wondered about and did a perfect job exploring with useful ablation studies.
      • KalMann4 hours ago
        I don&#x27;t really see how this implies the above commenter&#x27;s statement is &quot;simply not true&quot;.
        • traderj0e13 minutes ago
          What I got from this is the above comment was true.
      • taeric5 hours ago
        I don&#x27;t think std::find typically uses a sentinel, though?
      • BeetleB6 hours ago
        For that machine and compiler version, yes.
      • eggprices6 hours ago
        Except on Apple, where binary search always wins. Does anyone know why?
        • stephencanon6 hours ago
          Prior to the current generation Intel designs, Apple’s branch predictor tables were a good deal larger than Intel’s IIRC, so depending on benchmarking details it’s plausible that Apple Silicon was predicting every branch perfectly in the benchmark, while Intel had a more real-world mispredict rate. Perf counters would confirm.
    • SuperV12346 hours ago
      That&#x27;s not what the article is about.
  • srcreigh5 hours ago
    The algorithm description was a bit confusing for me.<p>The SIMD part is just in the last step, where it uses SIMD to search the last 16 elements.<p>The Quad part is that it checks 3 points to create 4 paths, but also it&#x27;s searching for the right block, not just the right key.<p>The details are a bit interesting. The author chooses to use the last element in each block for the quad search. I&#x27;m curious how the algorithm would change if you used the first element in each block instead, or even an arbitrary element.
  • jstanley7 hours ago
    As a teenager I spent a weekend thinking that if binary search was good, because it cuts the search space in half at every step, then wouldn&#x27;t a <i>ternary</i> search be better? Because we&#x27;d cut it into thirds at every step.<p>So instead of just comparing the middle value, we&#x27;d compare the one at the 1&#x2F;3 point, and if that turns out to be too low then we compare the value at the 2&#x2F;3 point.<p>Unfortunately although we cut the search space to 2&#x2F;3 of what it was for binary search at each step (1&#x2F;3 vs 1&#x2F;2), we do 3&#x2F;2 as many comparisons at each step (one comparison 50% of the time, two comparisons the other 50%), so it averages out to equivalence.<p>EDIT: See zamadatix reply, it&#x27;s actually 5&#x2F;3 as many comparisons because 2&#x2F;3 of the time you have to do 2.
    • zamadatix6 hours ago
      This ternary approach doesn&#x27;t actually average 3&#x2F;2 comparisons per level:<p>- First third: 1 comparisons<p>- Second third: 2 comparisons<p>- Third third: 2 comparisons<p>(1+2+2)&#x2F;3 = 5&#x2F;3 average comparisons. I think the gap starts here at assuming it&#x27;s 50% of the time because it feels like &quot;either you do 1 comparison or 2&quot; but it&#x27;s really 33% of the time because &quot;there is 1&#x2F;3 chance it&#x27;s in the 1st comparison and 2&#x2F;3 chance it&#x27;ll be 2 comparisons&quot;.<p>This lets us show ternary is worse in total average comparisons, just barely: 5&#x2F;3*Log_3[n] = 1.052... * Log_2[n].<p>In other words, you end up with fewer levels but doing more comparisons (on average) to get to the end. This is true for all searches of this type (w&#x2F; a few general assumptions like the values being searched for are evenly distributed and the cost of the operations is idealized - which is where the main article comes in) where the number of splits is &gt; 2.
      • jstanley6 hours ago
        Oh yeah!
        • krackers6 minutes ago
          If you sort of squint this idea does work in cases where the cost of comparison is dominated by the cost of going down a level. And that leads you to things like b-trees where fetching a page from disk is expensive but doing the comparisons within that page is basically free.
    • GuB-425 hours ago
      It turns out that teenager you had something.<p>Not for the ternary version of the binary search algorithm, because what you had is just a skewed binary search, not an actual ternary search. Because comparisons are binary by nature, any search algorithm involving comparisons are a type of binary search, and any choice other than the middle element is less efficient in terms of algorithmic complexity, though in some conditions, it may be better on real hardware. For an actual ternary search, you need a 3-way comparison as an elementary operation.<p>Where it gets interesting is when you consider &quot;radix efficiency&quot; [1], for which the best choice is 3, the natural number closest to e. And it is relevant to tree search, that is, a ternary tree may be better than a binary tree.<p>[1] <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Optimal_radix_choice" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Optimal_radix_choice</a>
    • ack_complete5 hours ago
      Note that CPUs have also gotten dramatically wider in both execution width and vector capability since you were a teenager. The increased throughput shifts the balance more toward being able to burn operations to reduce dependency chains. It&#x27;s possible for your idea to have been both non-viable on the CPUs at the time and more viable on CPUs now.
    • bryanlarsen6 hours ago
      Did you continue by fantasizing about CPU&#x27;s that contain ternary comparators?
    • nkurz6 hours ago
      &gt; Unfortunately although we cut the search space to 2&#x2F;3 of what it was for binary search at each step (1&#x2F;3 vs 1&#x2F;2), we do 3&#x2F;2 as many comparisons at each step (one comparison 50% of the time, two comparisons the other 50%), so it averages out to equivalence.<p>True, but is there some particular reason that you want to minimize the number of comparisons rather than have a faster run time? Daniel doesn&#x27;t overly emphasize it, but as he mentions in the article: &quot;The net result might generate a few more instructions but the number of instructions is likely not the limiting factor.&quot;<p>The main thing this article shows is that (at least sometimes on some processors) a quad search is faster than a binary search _despite_ the fact that that it performs theoretically unnecessary comparisons. While some computer scientists might scoff, I&#x27;d bet heavily that an optimized ternary search could also frequently outperform.
      • jstanley6 hours ago
        You normally measure runtime of a sorting algorithm in terms of the number of comparisons it has to do.<p>Obviously real-world performance depends on other things as well.
        • Someone6 hours ago
          Not “normally”, but “in computer science” and even then, mostly “in the past” and even then, only “typically” (there are sorting algorithms that make zero comparisons. See for example <a href="https:&#x2F;&#x2F;pages.cs.wisc.edu&#x2F;~paton&#x2F;readings&#x2F;Old&#x2F;fall01&#x2F;LINEAR-SORTS.html" rel="nofollow">https:&#x2F;&#x2F;pages.cs.wisc.edu&#x2F;~paton&#x2F;readings&#x2F;Old&#x2F;fall01&#x2F;LINEAR-...</a>)<p>All other people live in the real world, and care about real-world performance, and modern computer scientists know that.
          • alexfoo5 hours ago
            Those algorithms may not be doing any pairwise comparisons (e.g. between elements being sorted) but they still do plenty of comparisons.<p>And some of the algorithms, as described, still end up doing pairwise comparisons in all-but-optimal cases.<p>(Bucket sort requires items that end up in the same bucket to be sorted. This doesn&#x27;t happen automatically via the algorithm as stated. Radix sort requires the items at each &quot;level&quot; to be sorted. Neither algorithm specifies how this should be done without pairwise comparisons.)<p>Counting Sort does work without pairwise comparisons, but is only efficient for small ranges of values, and if that&#x27;s the case then it&#x27;s obvious you don&#x27;t need to apply a traditional sort if the number of elements greatly outnumbers the number of possible values.<p>Also, the algorithms still require some form of comparisons, just not pairwise comparisons.<p>&gt; All other people live in the real world, and care about real-world performance, and modern computer scientists know that.<p>Yes, completely agree with that, but traditional &quot;Comp Sci&quot; is built on small building blocks of counting &quot;comparisons&quot; or &quot;memory accesses&quot;. It&#x27;s not designed to analyse prospective performance given modern processors with L1&#x2F;L2&#x2F;L3 caches, branch prediction, SIMD instructions, etc.
    • compiler-guy5 hours ago
      This idea is closely related to the famous &quot;Stooge Sort&quot;, which is basically quicksort with the pivot at 1&#x2F;3 rather than 1&#x2F;2. Naively, one might think it is faster than Quicksort, but of course it isn&#x27;t.<p>For years--maybe still?--analyzing its running time was a staple of the first or second problem set in a college-level &quot;Introduction to Algorithms&quot; course.<p><a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Stooge_sort" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Stooge_sort</a>
    • eggprices6 hours ago
      When you can&#x27;t seek quickly, e.g. on a disk, you can use a B-tree with say 128-way search. Fetching 128 keys doesn&#x27;t cost much more than fetching 1 but it saves an additional 7 fetches.
    • madcaptenor6 hours ago
      Isn&#x27;t it a bit better on average, although not as much as you&#x27;d hoped? For example 19 steps of binary search get you down to 1&#x2F;524288 of the original search space with 19 comparisons. 12 steps of ternary search get you down to 1&#x2F;3^12 = 1&#x2F;531441 of the original search space with, on average, 12 * 3&#x2F;2 = 18 comparisons.
      • jstanley6 hours ago
        Maybe! But you can see the other comment that points out I was wrong and it is actually 5&#x2F;3 comparisons so it still works out worse.
    • bena6 hours ago
      Imagine if you split the search space N times, no middles. Then you could just compare the value.
    • matchooo05 hours ago
      [dead]
  • alexfoo5 hours ago
    The classical canonical Comp Sci algorithms are effectively &quot;designed&quot; for CPUs with no parallelism (either across multiple cores, via Hyper-threading technology, or &quot;just&quot; SIMD style instructions), and also where all memory accesses take the same amount of time (so no concept of L1&#x2F;L2&#x2F;L3&#x2F;etc caches of varying latencies). And all working on general&#x2F;random data.<p>As soon as you move away from either (or both) of these assumptions then there are likely to be many tweaks you can make to get better performance.<p>What the classical algorithms do offer is a very good starting point for developing a more optimal&#x2F;efficient solution once you know more about the specific shape of data or quirks&#x2F;features of a specific CPU.<p>When you start to get at the pointy end of optimising things then you generally end up looking at how the data is stored and accessed in memory, and whether any changes you can make to improve this don&#x27;t hurt things further down the line. In a job many many years ago I remember someone who spent way too long optimising a specific part of some code only to find that the overall application ran slower as the optimisations meant that a lot more information needed later on had been evicted from the cache.<p>(This is probably just another way of stating Rob Pike&#x27;s 5th rule of programming which was itself a restatement of something by Fred Brooks in _The Mythical Man Month_. Ref: <a href="https:&#x2F;&#x2F;www.cs.unc.edu&#x2F;~stotts&#x2F;COMP590-059-f24&#x2F;robsrules.html" rel="nofollow">https:&#x2F;&#x2F;www.cs.unc.edu&#x2F;~stotts&#x2F;COMP590-059-f24&#x2F;robsrules.htm...</a>)
  • gobdovan6 hours ago
    I thought this would be about how you can beat binary search in the &#x27;Guess Who?&#x27; game. There&#x27;s a cool math paper about it [0] and an approachable video by the author. [1]<p>[0] <a href="https:&#x2F;&#x2F;arxiv.org&#x2F;abs&#x2F;1509.03327" rel="nofollow">https:&#x2F;&#x2F;arxiv.org&#x2F;abs&#x2F;1509.03327</a><p>[1] <a href="https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=_3RNB8eOSx0" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=_3RNB8eOSx0</a>
    • thaumasiotes4 hours ago
      You can&#x27;t beat binary search in Guess Who. From the abstract:<p>&gt;&gt; Instead, the optimal strategy for the player who trails is to make certain bold plays in an attempt catch up.<p>The reason that&#x27;s optimal, if you&#x27;re losing, is that you assume that your opponent, who isn&#x27;t losing, is going to use binary search. They&#x27;re going to use binary search because it&#x27;s the optimal way to find the secret.<p>Since you&#x27;re behind, if you also use binary search, both players will progress toward the goal at the same rate, and you&#x27;ll lose.<p>Trying to get lucky means that you intentionally play badly in order to get more victories. You&#x27;re redistributing guesses taken between games in a negative-sum manner - you take more total guesses (because your search strategy is inferior to binary search), but they are unevenly distributed across your games, and in the relatively few games where you perform well above expectation, you can score a victory.
      • gobdovan2 hours ago
        You&#x27;re mixing two different objectives the paper presents. You can&#x27;t beat binary search when the objective is to minimise the expected number of turns <i>in a single player setting</i>.<p>However, in a two player setting, using the strategies presented in the paper, you will beat an adversary that uses binary search in more than 50% of the games played.<p>Here&#x27;s another visual demonstration: <a href="https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=zmvn4dnq82U" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=zmvn4dnq82U</a>
        • thaumasiotes1 hour ago
          What do you think you&#x27;re saying that I didn&#x27;t already say?<p>&gt; in a two player setting, using the strategies presented in the paper, you will beat an adversary that uses binary search in more than 50% of the games played.<p>This is technically true. But 50 percentage points of your &quot;more than 50%&quot; of games played are games where you exclusively use binary search. For the remainder, you&#x27;re redistributing luck around between potential games in a way that is negative-sum, exactly like I just said.
          • gobdovan16 minutes ago
            &gt; But 50 percentage points of your &quot;more than 50%&quot; of games played are games where you exclusively use binary search<p>Although I think I get your point, saying &#x27;You can&#x27;t beat binary search in Guess Who&#x27; is misleading, considering you would probably describe yourself the optimal strategy as &#x27;play binary search when ahead, when behind, don&#x27;t&#x27;.<p>&gt; Trying to get lucky means that you intentionally play badly in order to get more victories<p>That&#x27;s quite an uncommon definition of good and bad.
  • dicroce1 hour ago
    If you know about the distribution of keys you can do even better by factoring that knowledge into where you split.
  • layer83 hours ago
    …for 16-bit integers, and it’s still a binary search with the same asymptotic complexity, just a constant-factor speedup.
  • BeetleB6 hours ago
    Some of the plots would have been much more helpful if instead of absolute value in seconds, the y-axis were the multiplier w.r.t binary search (and eyeballing suggests a relatively constant multiplier).<p>Obviously, this isn&#x27;t changing the big-Oh complexity, but in the &quot;real world&quot;, still nice to see a 2-4x speedup.
  • aidenn07 hours ago
    If you are storing 16-bit integers, wouldn&#x27;t an 8kB bitmap be even faster?
    • loeg5 hours ago
      The library the author is talking about selects between bitmap and array dynamically depending on density.<p><a href="https:&#x2F;&#x2F;roaringbitmap.org&#x2F;" rel="nofollow">https:&#x2F;&#x2F;roaringbitmap.org&#x2F;</a>
    • Findecanor6 hours ago
      The range is 1..4096, so 4096 bits = 512 byte bitmap would suffice.<p>That is, if you&#x27;re only ever going to test for membership in the set. If you need metadata then ... You could store that in a packed array and use a population count of the bit-vector before the lookup bit as index into it. For each word of bits, store the accumulated population count of the words before it to speed up lookup. Modern CPU&#x27;s are memory-bound so I don&#x27;t think SIMD would help much over using 64-bit words. For 4096 bits &#x2F; 64, that would be 64 additional bytes.
  • quirino5 hours ago
    On optimizing binary search: <a href="https:&#x2F;&#x2F;en.algorithmica.org&#x2F;hpc&#x2F;data-structures&#x2F;binary-search&#x2F;" rel="nofollow">https:&#x2F;&#x2F;en.algorithmica.org&#x2F;hpc&#x2F;data-structures&#x2F;binary-searc...</a>
    • garaetjjte4 hours ago
      I once did have a need for binary search in memory mapped files and I experimented with Eytzinger layout (which I learned from <a href="https:&#x2F;&#x2F;bannalia.blogspot.com&#x2F;2015&#x2F;06&#x2F;cache-friendly-binary-search.html" rel="nofollow">https:&#x2F;&#x2F;bannalia.blogspot.com&#x2F;2015&#x2F;06&#x2F;cache-friendly-binary-...</a>). It turned out that it was slower than plain binary search, I think because keys I was looking up were often clumped together thus it played quite well with cache anyway.
  • amelius38 minutes ago
    I always wondered if we could get any faster than O(log n). Glad we&#x27;re making progress!
  • senfiaj4 hours ago
    The title is slightly misleading, I mean yes, naive binary search might have larger constant but the algorithm is still O(log(n)). This is still some &quot;divide and conquer&quot; style algorithm just with bunch of CPU specific optimizations. Also this works well with simple data structures, like integers, with more complex objects (custom comparators) it matters less.
    • pfortuny3 hours ago
      The complexity of binary search in terms of &quot;search&quot; (comparison) operations is exactly log_2(n)+1, not just O(n). This algorithm just uses modern and <i>current</i> processor architecture artifacts to &quot;improve&quot; it on arrays of up to 4096 elements.<p>So not exactly &quot;n&quot; as in O(n).<p>Also: only for 16-bit integers.
      • senfiaj3 hours ago
        &gt; The complexity of binary search in terms of &quot;search&quot; (comparison) operations is exactly log_2(n)+1, not just O(n)<p>&gt; So not exactly &quot;n&quot; as in O(n).<p>For large enough inputs the algorithm with better Big O complexity will eventually win (at least in the worst cases). Yes, sometimes it never happens in practice when the constants are too large. But say 100 * n * log(n) will eventually beat 5 * n for large enough n. Some advanced algorithms can use algorithms with worse Big O complexity but smaller constants for small enough sub-problems to improve performance. But it&#x27;s more like to optimization detail rather than a completely different algorithm.<p>&gt; This algorithm just uses modern and current processor architecture artifacts to &quot;improve&quot; it on arrays of up to 4096<p>Yes, that&#x27;s my point. It&#x27;s basically &quot;I made binary search for integers X times faster on some specific CPUs&quot;. &quot;Beating binary search&quot; is somewhat misleading, it&#x27;s more like &quot;microptimizing binary search&quot;.
    • cubefox4 hours ago
      &gt; The title is slightly misleading, I mean yes, naive binary search might have larger constant but the algorithm is still O(log(n)).<p>I think the title is not misleading since the Big O notation is only supposed to give a rough estimate of the performance of an algorithm.<p>(I agree though that binary search is already extremely fast, so making something twice as fast won&#x27;t move the needle for the vast majority of applications where the speed bottleneck is elsewhere. Even infinite speed, i.e. instant sorted search, would likely not be noticeable for most software.)
      • senfiaj3 hours ago
        For me it&#x27;s slightly misleading because it&#x27;s almost like saying &quot;I wrote a faster quicksort implementation, so it beats quicksort!&quot;. In this case the binary search fundamental idea of &quot;divide and conquer&quot; is still there, the article just does microptimizations (which seem to be not very portable and are less relevant&#x2F;applicible for more complex data structures) in order to reduce the constant part.<p>Yes, algorithmic complexity is theoretical, it often ignores the real world constants, but they are usually useful when comparing algorithms for larger inputs, unless we are talking about &quot;galactic algorithms&quot; with insanely large constants.
  • bediger40002 days ago
    The (AI generated?) image on this article is absolutely not helpful, and I think it&#x27;s wrong based on how I read the article. Better not to have an image at all.
    • crazygringo5 hours ago
      Seriously. It makes it seem like this is going to be a blog post either intended for elementary school students, or more likely for teachers on how to better explain some arithmetic concept to elementary school students.<p>It&#x27;s absolutely bizarre. Images communicate meaning. Much better to have no image than to have an image that is completely misleading about the target audience or level of technical sophistication.
    • iosovi7 hours ago
      Agreed, it threw me off at first but the rest of the article was quite nice.
  • gobdovan6 hours ago
    I remember I had a pedagogy class in Uni taught by psychology faculty, and was messing with them by proposing a mock syllabus where we&#x27;d teach students binary search, then the advanced advanced ones ternary search, and the very advanced, Quaternary, with a big Q, as in the geological period. Jokes on me now, I suppose.
  • wood_spirit7 hours ago
    A beautiful algorithm.<p>Would there be any value in using simd to check the whole cache line that you fetch for exact matches on the narrowing phase for an early out?
  • attractivechaos1 hour ago
    See also: Static search trees: 40x faster than binary search<p>- <a href="https:&#x2F;&#x2F;curiouscoding.nl&#x2F;slides&#x2F;p99-text&#x2F;" rel="nofollow">https:&#x2F;&#x2F;curiouscoding.nl&#x2F;slides&#x2F;p99-text&#x2F;</a><p>- <a href="https:&#x2F;&#x2F;curiouscoding.nl&#x2F;posts&#x2F;static-search-tree&#x2F;" rel="nofollow">https:&#x2F;&#x2F;curiouscoding.nl&#x2F;posts&#x2F;static-search-tree&#x2F;</a><p>- <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=42562847">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=42562847</a> (656 points; 232 comments)
  • kardos6 hours ago
    So is the SIMD the magic piece here, or is it the interpolation search? If the data is evenly distributed, that is pretty optimal for the interpolation search..
    • mayoff6 hours ago
      In the Intel CPU + cold cache case, the quad search matters. In the other three cases, only the SIMD matters.
      • loeg5 hours ago
        To put it another way: this is addressed in the article.
  • vasco3 hours ago
    This was the entry level project we did in a hardware optimization course I took maybe 15 years ago, using SIMD instructions. Lots of things can be naively optimized by unrolling any loops like this. Compilers do some of this themselves.
  • nullc1 hour ago
    You can improve interpolated search by monitoring progress and if it&#x27;s not converging fast enough, alternate with bisection steps. (and, as clear from the article, switch to linear&#x2F;vector scanning when the range is small emough).<p>Often when an interpolated search is wrong the interpolation will tend to nail you against one side or the other of the range-- so the worst case is linear. By allowing only a finite number of failed probes (meaning they only move the same boundary as last time, an optimally working search will on average alternate hi&#x2F;lo) you can maintain the log guarantee of bisection.
  • owlcompliance5 hours ago
    What about non-binary search?
  • jonfe-darontos5 hours ago
    And here I thought this was going to be related to quaternions
  • peter_d_sherman3 hours ago
    &gt;&quot;Virtually all processors today have data parallel instructions (sometimes called SIMD) that can check several values at once.<p>[...]<p><i>The binary search checks one value at a time. However, recent processors can load and check more than one value at once. They have excellent memory-level parllelism. This suggest that instead of a binary search, we might want to try a quaternary search...</i>&quot;<p>First of all, brilliant observations! (Overall, a great article too!)<p>Yes, today&#x27;s processors indeed have a parallelism which was unconceived of at the time the original Mathematicians, then-to-be Computer Scientists, conceived of Binary Search...<p>Now I myself wonder if these ideas might be extended to GPU&#x27;s, that is, if the massively parallel execution capability of GPU&#x27;s could be extended to search for data like Binary Search does, and what such an appropriately parallelized algorithm&#x2F;data structure would look like... keep in mind, if we consider an updateable data structure, then that means that parts of it may need to be appropriately locked at the same time that multiple searches and updates are occurring simultaneously... so what data structure&#x2F;algorithm would be the most efficient for a massively parallel scenario like that?<p>Anyway, great article and brilliant observations!
  • gowld3 hours ago
    Previous related: <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=47726340">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=47726340</a><p>40x Faster Binary Search - This talk will first expose the lie that binary search takes O(lg n) time — it very much does not! Instead, we will see that binary search has only constant overhead compared to an oracle. Then, we will exploit everything that modern CPUs have to offer (SIMD, ILP, prefetching, efficient caching) in order to gain 40x increased throughput over the Rust standard library implementation.
  • aamargulies4 hours ago
    Here&#x27;s my version with a key spline improvement. I should really write this up...<p>#include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; #include &lt;arm_neon.h&gt;<p>&#x2F;* Author: aam@fastmail.fm * * Apple M4 Max (P-core) variant of simd_quad which uses a key spline * to great effect (blog post summary incoming!) <i>&#x2F; bool simd_quad_m4(const uint16_t </i>carr, int32_t cardinality, uint16_t pos) { enum { gap = 64 };<p><pre><code> if (cardinality &lt; gap) { if (cardinality &gt;= 32) { &#x2F;&#x2F; 32 &lt;= n &lt; 64: NEON-compare the first 32 as a single x4 load, &#x2F;&#x2F; sweep the remainder. uint16x8_t needle = vdupq_n_u16(pos); uint16x8x4_t v = vld1q_u16_x4(carr); uint16x8_t hit = vorrq_u16( vorrq_u16(vceqq_u16(v.val[0], needle), vceqq_u16(v.val[1], needle)), vorrq_u16(vceqq_u16(v.val[2], needle), vceqq_u16(v.val[3], needle))); if (vmaxvq_u16(hit) != 0) return true; for (int32_t j = 32; j &lt; cardinality; j++) { uint16_t x = carr[j]; if (x &gt;= pos) return x == pos; } return false; } if (cardinality &gt;= 16) { &#x2F;&#x2F; 16 &lt;= n &lt; 32: paired x2 load + sweep tail. uint16x8_t needle = vdupq_n_u16(pos); uint16x8x2_t v = vld1q_u16_x2(carr); uint16x8_t hit = vorrq_u16(vceqq_u16(v.val[0], needle), vceqq_u16(v.val[1], needle)); if (vmaxvq_u16(hit) != 0) return true; for (int32_t j = 16; j &lt; cardinality; j++) { uint16_t x = carr[j]; if (x &gt;= pos) return x == pos; } return false; } if (cardinality &gt;= 8) { &#x2F;&#x2F; 8 &lt;= n &lt; 16: single 128-bit compare + sweep tail. uint16x8_t needle = vdupq_n_u16(pos); uint16x8_t v = vld1q_u16(carr); if (vmaxvq_u16(vceqq_u16(v, needle)) != 0) return true; for (int32_t j = 8; j &lt; cardinality; j++) { uint16_t x = carr[j]; if (x &gt;= pos) return x == pos; } return false; } for (int32_t j = 0; j &lt; cardinality; j++) { uint16_t v = carr[j]; if (v &gt;= pos) return v == pos; } return false; } int32_t num_blocks = cardinality &#x2F; gap; int32_t base = 0; int32_t n = num_blocks; while (n &gt; 3) { int32_t quarter = n &gt;&gt; 2; int32_t k1 = carr[(base + quarter + 1) * gap - 1]; int32_t k2 = carr[(base + 2 * quarter + 1) * gap - 1]; int32_t k3 = carr[(base + 3 * quarter + 1) * gap - 1]; int32_t c1 = (k1 &lt; pos); int32_t c2 = (k2 &lt; pos); int32_t c3 = (k3 &lt; pos); base += (c1 + c2 + c3) * quarter; n -= 3 * quarter; } while (n &gt; 1) { int32_t half = n &gt;&gt; 1; base = (carr[(base + half + 1) * gap - 1] &lt; pos) ? base + half : base; n -= half; } int32_t lo = (carr[(base + 1) * gap - 1] &lt; pos) ? base + 1 : base; if (lo &lt; num_blocks) { const uint16_t *blk = carr + lo * gap; uint16x8_t needle = vdupq_n_u16(pos); uint16x8x4_t a = vld1q_u16_x4(blk); uint16x8x4_t b = vld1q_u16_x4(blk + 32); uint16x8_t h0 = vorrq_u16( vorrq_u16(vceqq_u16(a.val[0], needle), vceqq_u16(a.val[1], needle)), vorrq_u16(vceqq_u16(a.val[2], needle), vceqq_u16(a.val[3], needle))); uint16x8_t h1 = vorrq_u16( vorrq_u16(vceqq_u16(b.val[0], needle), vceqq_u16(b.val[1], needle)), vorrq_u16(vceqq_u16(b.val[2], needle), vceqq_u16(b.val[3], needle))); return vmaxvq_u16(vorrq_u16(h0, h1)) != 0; } for (int32_t j = num_blocks * gap; j &lt; cardinality; j++) { uint16_t v = carr[j]; if (v &gt;= pos) return v == pos; } return false;</code></pre> }<p>&#x2F;* * Spine variant, M4 edition. * * pack the interpolation probe keys into a dense contiguous region so the * cold-cache pointer chase streams through consecutive cache lines: * * n=4096 -&gt; 64 spine keys -&gt; 128 B = 1 M4 cache line * n=2048 -&gt; 32 spine keys -&gt; 64 B = half a line * n=1024 -&gt; 16 spine keys -&gt; 32 B * * The entire interpolation phase for a max-sized Roaring container now * lives in one cache line. The final SIMD block check still loads from * carr. * * The num_blocks &lt;= 3 fallback: * with very few blocks the carr-based probes accidentally prime the final * block&#x27;s lines, which the spine path disrupts. <i>&#x2F; bool simd_quad_m4_spine(const uint16_t </i>carr, const uint16_t <i>spine, int32_t cardinality, uint16_t pos) { enum { gap = 64 };<p><pre><code> if (cardinality &lt; gap) { &#x2F;&#x2F; Same fast paths as simd_quad_m4 -- spine is irrelevant here. if (cardinality &gt;= 32) { uint16x8_t needle = vdupq_n_u16(pos); uint16x8x4_t v = vld1q_u16_x4(carr); uint16x8_t hit = vorrq_u16( vorrq_u16(vceqq_u16(v.val[0], needle), vceqq_u16(v.val[1], needle)), vorrq_u16(vceqq_u16(v.val[2], needle), vceqq_u16(v.val[3], needle))); if (vmaxvq_u16(hit) != 0) return true; for (int32_t j = 32; j &lt; cardinality; j++) { uint16_t x = carr[j]; if (x &gt;= pos) return x == pos; } return false; } if (cardinality &gt;= 16) { uint16x8_t needle = vdupq_n_u16(pos); uint16x8x2_t v = vld1q_u16_x2(carr); uint16x8_t hit = vorrq_u16(vceqq_u16(v.val[0], needle), vceqq_u16(v.val[1], needle)); if (vmaxvq_u16(hit) != 0) return true; for (int32_t j = 16; j &lt; cardinality; j++) { uint16_t x = carr[j]; if (x &gt;= pos) return x == pos; } return false; } if (cardinality &gt;= 8) { uint16x8_t needle = vdupq_n_u16(pos); uint16x8_t v = vld1q_u16(carr); if (vmaxvq_u16(vceqq_u16(v, needle)) != 0) return true; for (int32_t j = 8; j &lt; cardinality; j++) { uint16_t x = carr[j]; if (x &gt;= pos) return x == pos; } return false; } for (int32_t j = 0; j &lt; cardinality; j++) { uint16_t v = carr[j]; if (v &gt;= pos) return v == pos; } return false; } int32_t num_blocks = cardinality &#x2F; gap; if (num_blocks &lt;= 3) { return simd_quad_m4(carr, cardinality, pos); } int32_t base = 0; int32_t n = num_blocks; &#x2F;&#x2F; Pull the whole spine into L1 up front. For n in [256, 4096] this is &#x2F;&#x2F; 1 line (128 B); for smaller n it is a partial line. Cheap on cold. __builtin_prefetch(spine); while (n &gt; 3) { int32_t quarter = n &gt;&gt; 2; int32_t k1 = spine[base + quarter]; int32_t k2 = spine[base + 2 * quarter]; int32_t k3 = spine[base + 3 * quarter]; int32_t c1 = (k1 &lt; pos); int32_t c2 = (k2 &lt; pos); int32_t c3 = (k3 &lt; pos); base += (c1 + c2 + c3) * quarter; n -= 3 * quarter; } while (n &gt; 1) { int32_t half = n &gt;&gt; 1; base = (spine[base + half] &lt; pos) ? base + half : base; n -= half; } int32_t lo = (spine[base] &lt; pos) ? base + 1 : base; if (lo &lt; num_blocks) { const uint16_t *blk = carr + lo * gap; uint16x8_t needle = vdupq_n_u16(pos); uint16x8x4_t a = vld1q_u16_x4(blk); uint16x8x4_t b = vld1q_u16_x4(blk + 32); uint16x8_t h0 = vorrq_u16( vorrq_u16(vceqq_u16(a.val[0], needle), vceqq_u16(a.val[1], needle)), vorrq_u16(vceqq_u16(a.val[2], needle), vceqq_u16(a.val[3], needle))); uint16x8_t h1 = vorrq_u16( vorrq_u16(vceqq_u16(b.val[0], needle), vceqq_u16(b.val[1], needle)), vorrq_u16(vceqq_u16(b.val[2], needle), vceqq_u16(b.val[3], needle))); return vmaxvq_u16(vorrq_u16(h0, h1)) != 0; } for (int32_t j = num_blocks * gap; j &lt; cardinality; j++) { uint16_t v = carr[j]; if (v &gt;= pos) return v == pos; } return false;</code></pre> }<p>&#x2F;&#x2F; Build the spine for a given carr. Caller allocates cardinality&#x2F;64 u16s. void simd_quad_m4_build_spine(const uint16_t </i>carr, int32_t cardinality, uint16_t <i>spine) { enum { gap = 64 }; int32_t num_blocks = cardinality &#x2F; gap; for (int32_t i = 0; i &lt; num_blocks; i++) { spine[i] = carr[(i + 1) </i> gap - 1]; } }
  • m3kw94 hours ago
    Will I get a job if i say i can beat binary search?
  • samagragune5 hours ago
    [dead]
  • debo_6 hours ago
    [dead]
  • saberience6 hours ago
    [flagged]
  • cubefox6 hours ago
    Since binary search is already very fast with its O(log n) time complexity: are there any real world applications which could practically benefit from this improvement?
    • senfiaj4 hours ago
      I guess it matters if you have to do lookup in a tight loop. If you do this occasionally, I think it&#x27;s not worth it, especially for complex objects with custom comparators. The algorithm is still O(log(n)) just a more advanced &quot;divide and conquer&quot; with smaller constant.
      • VorpalWay2 hours ago
        I would expect the standard library of various languages to provide an optimised implementation such as this. Then everyone downstream benefits, and benefits from future improvements when compiled for a newer version of the language &#x2F; executed under a newer version of the runtime.<p>You see this in rust, where they replaced the hash tables many years ago, the channel a couple of years ago, and most recently the sort implementations for both stable and unstable sort. I expect other languages &#x2F; runtimes do similar things over time as well as CPUs change and new approaches are discovered.
        • leni5361 hour ago
          I wouldn&#x27;t. This is very specialized to the type of the elements.
    • loeg5 hours ago
      This is a drop-in improvement for essentially any binary search over 16-bit integer members.
      • cubefox5 hours ago
        With &quot;practically benefit&quot; I meant a speedup that is noticable. Is there any software that is significantly bottlenecked by the speed of sorted search?