Manuscript Offprint
arXiv:2611.06745Generalized Sorting via Four-Cycles
Abstract
We study the generalized sorting problem where only a subset of the pairs can be compared. Equivalently, we are given an -vertex -edge graph where the vertex set is to be sorted, and the edge set indicates possible comparisons. The goal is to sort with as few (adaptive) queries to as possible.
When is the complete graph, the problem is equivalent to standard sorting for which queries are sufficient and necessary. All classical sorting algorithms crucially rely on the ability to compare any pair and do not imply an -query algorithm in the general case. This was improved 15 years ago by Huang, Kannan, and Khanna [FOCS'11] who achieved a bound of . Kuszmaul and Narayanan [FOCS'21] later gave a bound of , which is more efficient for sparse graphs, but matches the barrier for dense graphs.
In this paper, we present an algorithm for generalized sorting that makes at most queries, therefore breaking the longstanding barrier for all graphs. The key to our result is to query edges that belong to many (specific types of) four-cycles. We show that querying such edges allows the algorithm to verify the direction of many other edges (specifically, their opposing edges in the four-cycles) and thus achieve a much better amortized query cost.
*Supported in part by NSF CAREER Award CCF 2442812, a Sloan Fellowship, and a Google Research Award.
1 Introduction
The standard sorting problem assumes that any pair of elements can be compared. A well-studied generalization, known as the generalized sorting problem [HKK11], removes this freedom. We are given a simple undirected graph on vertices and edges. The vertices have an unknown total order , and a query on reveals whether or . Queries outside are forbidden. We are promised that consecutive vertices in the true order are joined by an edge. Equivalently, directing every allowed edge according to produces an acyclic graph with a directed Hamiltonian path. The task is to recover this order using few queries.
Background: If is the complete graph, then the problem is equivalent to classical comparison-based sorting for which queries are sufficient and necessary. Another well-studied special case of the generalized sorting problem is when is the complete bipartite graph, which is known as the nuts-and-bolts matching problem. For this variant, too, a long line of work eventually achieved the optimal query complexity of [Raw92; Alo+94; BF95; Bra95; ABF96; KMS98].
The situation is much less understood for general graphs. The trivial algorithm is to use up to queries to learn the direction of every edge in the graph to discover the directed Hamiltonian path. Huang, Kannan, and Khanna [HKK11] were the first to break this bound. They proved 15 years ago that there is a randomized generalized sorting algorithm with query complexity . Roughly speaking, their algorithm iteratively discovers ordered sets of length using queries. Repeating this times achieves the claimed query complexity. A more recent algorithm by Kuszmaul and Narayanan [KN21]—building on the work of Lu et al. [Lu+21]—achieves a bound of . Their algorithm keeps querying the edges of uniformly at random until these queries become very unlikely to discover “inversions”, at which point they switch to the prediction-based algorithm of [Lu+21].
The algorithms of [HKK11] and [KN21] achieve the same bound of for general graphs using very different approaches. This is also a natural bound for various other graph problems. For example, is provably the right bound for vertex coloring under neighbor and pair queries [ACK19], and for one-sided testing of graph isomorphism under adjacency-matrix queries [FM08]. The same bound is optimal in quantum query complexity, for problems such as graph connectivity, minimum spanning tree [Dür+06], and testing graph planarity or acyclicity [CK12], among many others. It is therefore natural to ask:
Is the right bound for generalized sorting?
Our result: In this paper, we break through the longstanding barrier for generalized sorting, showing that it is indeed not the right bound. More specifically, we prove that:
Theorem 1. Generalized sorting on an -vertex graph admits a randomized polynomial-time algorithm that succeeds with probability and makes at most queries.
Our key ingredient to prove Theorem 1 is to query edges that belong to many (specific types of) length-four cycles that are abundant in dense graphs. We show that querying such edges allows the algorithm to verify the direction of many other edges (specifically, their opposing edges in the four-cycles) and thus achieve a much better amortized query cost. We give an overview of this idea and the overall proof in Section 2.
Further related work: Generalized sorting builds on earlier work on restricted comparisons and nonuniform comparison costs. Charikar et al. [Cha+00] first introduced the priced-information framework, evaluating query strategies against the cost of a cheapest certificate. Within this framework, Gupta and Kumar [GK01] studied sorting and selection with structured comparison costs, and Kannan and Khanna [KK03] studied selection with monotone comparison costs.
Another related line of work studies monotonicity testing, including whether an array of numbers is sorted or far from sorted, using few queries. Each query reveals an array entry, and the distance to sortedness is the minimum fraction of entries that must be changed to make the array nondecreasing. Sortedness testing, tolerant testing, and extensions to partially ordered domains have been studied extensively; see, e.g., [Erg+98; Fis+02; Fis04; Ail+04; PRR06; SS10; Ras16; Bel18; Ron25; Yos26] and the references therein.
Inversions, and an overview of [KN21]: Let us start by reviewing the concept of inversions, introduced in the work of [HKK11] and further utilized by [KN21] to achieve their query algorithm.
Let be the set of all permutations of that do not contradict any of the queries made so far. For any unqueried edge let its implied direction be the direction it takes in the majority of (breaking ties arbitrarily). We say that an edge is an inversion if its true direction differs from its implied direction. Now suppose that we query edges uniformly at random. If an inversion is found, it invalidates at least half of the permutations in . In this case, we update and all the implied directions. Since initially, this happens at most times, and the total cost of these queries is at most . If no inversion is found, then the total number of inversions must be at most w.h.p., and so the implied directions predict the true directions highly accurately. At this point, [KN21] plug in the algorithm of [Lu+21] which recovers the true order from a prediction with errors using queries. The combined query cost is . Choosing , gives the bound.
Key ingredient: inversions and witnesses: In the argument above, inversions are valuable because they reduce the solution space. Our algorithm also makes progress by finding inversions, but does so in a very different way. We call a cycle on 4 vertices a witness if its implied edge directions are exactly as in Figure 2.1. Now suppose that 3 queries confirm the directions of , , but reveal to be an inversion. In this case, we automatically infer to be predicted correctly.
At first, it may not seem that useful to make 3 queries only to confirm the direction of 4 edges. And indeed, that's not what we do. We show that if the graph is dense enough, then an average edge belongs to many witnesses, and so finding an inversion and querying its incident edges verifies the direction of a significant number of opposing edges. The effect of this (despite having a higher cost for querying all incident edges) is much more drastic than reducing the solution space by a constant. Let us describe this intuition further by considering random graphs first.

Figure 2.1: A four-cycle witness.
Existence of many witnesses (random graphs). First, observe that we can equivalently view witnesses as four-cycles in a bipartite graph. To see this, take two copies of every vertex , denoted by and . For every predicted edge , we add an undirected edge between and . This gives us a bipartite graph with vertices on each side and edges. As illustrated below, every four-cycle in corresponds exactly to a witness in the original graph: a four-cycle on corresponds to the four predicted edges .

Now, for intuition, suppose that this bipartite graph is a random -regular bipartite graph. Consider any two vertices on the left side and two vertices on the right side. These four vertices form a four-cycle if all four edges between them are present. In a random -regular bipartite graph, the probability of this happening is approximately . Since there are choices of such four vertices, the expected number of four-cycles is . Since the graph has edges and each four-cycle contains four edges, the average number of four-cycles containing an edge is
Thus, at least in this random setting, when is sufficiently large, there are many witnesses and an edge belongs to many witnesses on average.
Now suppose that we find an inversion on an edge that belongs to the average number of witnesses, and that most of its witnesses have correctly predicted side edges. By querying all edges adjacent to its endpoints, we can verify the directions of edges using only queries. Thus, the amortized query cost per verified edge is
Since there are edges in our bipartite graph, this suggests that we can verify all edges with only queries. To see why this is useful, consider two cases. If , then , giving us the desired bound. Otherwise, if , we can simply use the algorithm of [KN21], which makes queries. Thus, combining these two approaches suggests an query algorithm. Of course, this argument assumes that we can find inversions on edges with many witnesses, and that most of these witnesses have correctly predicted side edges. The main technical challenge is to guarantee these two properties, which we address next.
Existence of many witnesses (non-random graphs). Fortunately, the existence of many witnesses is not just a property of random graphs. Claim 1 proves that any bipartite graph with vertices on each side and edges contains at least four-cycles, provided that . (The latter condition is automatically satisfied as otherwise the query algorithm of [KN21] already takes queries.) For , this gives the same lower bound that we obtained for random -regular bipartite graphs.
However, this does not imply that every edge belongs to many witnesses. There could be some edges that belong to very few witnesses, while others belong to significantly more. To deal with this, we repeatedly remove edges that belong to fewer than witnesses among the remaining edges. We call these edges peeled, and the remaining edges form the core. By definition, every edge in the core belongs to at least witnesses.
The key observation is that we cannot peel too many edges. Suppose that we peel edges. Every witness consisting entirely of peeled edges can be charged to its first peeled edge. Since each edge is peeled when it belongs to fewer than remaining witnesses, the total number of such witnesses is less than . On the other hand, our four-cycle lower bound tells us that, if is sufficiently large, there must be at least witnesses among the peeled edges. Combining these bounds gives
where the last inequality holds by choosing a suitable constant in the definition of . Thus, even in non-random graphs, at most half of the edges are peeled, and every edge remaining in the core belongs to witnesses.
Bounding inversions around each vertex. The next challenge is to ensure that most witnesses of an inverted edge have correctly predicted side edges. For now, we continue with the regular case, where the degrees of all vertices in the original graph are . We use a modification of an algorithm from [Jia+24] that makes queries and guarantees that every vertex has at most adjacent inversions. Roughly speaking, this algorithm works by going through each vertex and sampling adjacent edges looking for inversions. If an inversion is found, we update our predictions. As discussed earlier, this can happen only times, since each inversion reduces the solution space by a constant factor. Otherwise, if no inversion is found, then with high probability at most of the edges adjacent to are incorrectly predicted. Some additional care is needed to make these predictions consistent across all vertices, but this can be done within the same query bound.
Now suppose that we find an inversion at an edge in the core. Recall that this edge belongs to at least witnesses. Since each of and has at most adjacent inversions, and each such inversion can affect at most witnesses, at most witnesses have an incorrectly predicted side edge. By choosing the hidden constants in our local error guarantee sufficiently small relative to the threshold , we guarantee that at least half of the witnesses have both side edges predicted correctly. Thus, querying all edges adjacent to and verifies the directions of edges, using only queries. This is exactly what we wanted.
Finding inversions in the core. It remains to explain how we find these inversions efficiently. Our algorithm samples edges uniformly at random from the core. If we find an inversion, we query all edges adjacent to its endpoints, verify the opposite edges of its witnesses, and repeat the process, including the peeling step. Since every such expansion verifies edges with queries, the total query complexity of finding and expanding inversions is
On the other hand, if we do not find an inversion in our random sample, then with high probability there are at most inversions remaining in the core. In this case, we simply keep the predicted directions of these edges and defer them to be resolved later by the algorithm of [Lu+21].
Thus, using queries, we can verify some edges, defer some others with at most incorrect predictions, and peel at most half of the remaining edges. This is the main guarantee that we need from our algorithm.
Handling general graphs. So far, we have assumed that the degrees of all vertices are . In general, however, some vertices may have much larger degrees than others. To handle this, we partition the vertices into buckets according to their degrees among the currently unknown edges. More specifically, we put vertices with degrees between and into the same bucket, and then partition the predicted edges according to the buckets of their endpoints. We process each edge bucket separately, using a witness threshold that depends on the maximum degrees of its two endpoints. This allows us to apply essentially the same argument as above, but with different degree bounds for different buckets. By summing over all buckets, we obtain the same guarantees, up to logarithmic factors.
Finally, we repeatedly apply this procedure to the peeled edges, setting when unknown edges remain. Since at most half of the edges are peeled in each round, we need only rounds. We stop when the number of remaining edges drops below a threshold , at which point we use the prediction-based approach to handle them with additional queries. The total query complexity is therefore
Choosing balances the two terms and gives our query bound.
3 Preliminaries
For the remainder of this paper, we assume that all logs are natural (base ) and that and are sufficiently large to overpower constants.
In this section, we describe two algorithms from previous work that will be used to help create our algorithm. We claim no novelty for either result. The first is a modified version of an algorithm from [Jia+24, Lemma 5.1]. The original algorithm takes a graph and gives a prediction for the direction of every edge using queries and guarantees, with high probability, that no vertex has more than adjacent errors. The modification we present uses the same techniques, but instead takes in an additional parameter and uses queries to get a prediction with at most errors adjacent to for every and a failure probability at most .
The following lemma gives a global prediction that incorrectly predicts few directions for each vertex. The proof more or less follows from [Jia+24, Lemma 5.1]. We present the needed modifications to their proof in Section B.
Lemma 1. Given a graph , a set of known edge directions , a set of edges with unknown direction , and a parameter . There exists a randomized algorithm that, with probability and queries, fixes a prediction of edge directions for each edge in such that
Where is the degree of among unknown edges in , and is the number of incorrectly predicted edges in adjacent to .
At a high level, the algorithm begins with a subroutine from [HKK11] that predicts edges and guarantees that each incorrectly predicted edge, when revealed, reduces the number of valid vertex orderings by a constant factor. This subroutine takes polynomial time and uses no queries. An algorithm that loops through all possible permutations and selects the more common edge direction would give this guarantee, but at the cost of exponential time. With recomputation, this subroutine can be wrong only times. Thus, we go through each vertex and sample adjacent edges looking for inversions. If we find one, we recompute. Otherwise, we fix a prediction for all edges adjacent to that vertex. Lastly, at the end of the prediction, we must resolve the fact that two endpoints of an edge may disagree with one another. We describe this in more detail in Section B.
The second algorithm we give is PredictionSort from [Lu+21]. This algorithm takes in a graph and a prediction of every edge direction and determines the true direction of every edge in , where is the number of incorrect predictions. We use this algorithm as a black-box and also assume the following lemma about it without proof, as it is the main result of [Lu+21, Theorem 1.1].
Lemma 2. There is a polynomial-time randomized algorithm PredictionSort that solves the generalized sorting problem in queries with probability for any constant .
We also note that combining LocalPredict and PredictionSort recovers the guarantees (up to log factors) of the algorithm of [KN21] by using the parameter . If we use this parameter, we will find a prediction in queries, and the number of errors adjacent to each vertex will be at most . Summing over vertices gives at most total errors. Plugging this into PredictionSort gives a solution in queries.
4 Main Algorithm FourCycleSort
In this section, we give the main algorithm FourCycleSort and its helper Reduce, as well as the analysis of their correctness, assuming some key lemmas that will be proven later. This section effectively serves as scaffolding for Section 5 and Section 6, which contain the main technical contributions of the paper. We begin by assuming the following lemma about a subroutine Reduce that we will prove later in Section 6.
We note that this degree among unknown edges in is fixed at the start of the algorithm and does not change after queries reveal edge directions.
Lemma 3. Given a graph , a set of known edge directions , a subset of unknown edges given by FourCycleSort (Algorithm 1), and a parameter . There is a randomized algorithm Reduce(V, E, Q, E', r) (Algorithm 2) that, with probability and in queries, either peels, defers, or certifies every edge in with the following guarantees.
-
The deferred edges come with a predicted direction that is wrong at most times.
-
There are at most peeled edges.
For Reduce, we always set where is the number of unknown edges, as already-certified edges do not affect query complexity. This gives an query algorithm that certifies some edges, defers some others with a prediction that is wrong at most times, and peels at most half of them.
With this subroutine in hand, the structure of our overall algorithm becomes: While is large, i.e., more than , run Reduce on the peeled edges. This can happen at most times. Once is small, run the LocalPredict with parameter , which will also take queries and add these predictions to the deferred predictions from each round of Reduce. After this, run PredictionSort and return the answer. The choice of comes from a balancing between from Reduce and from LocalPredict. In addition, the total number of incorrect predictions will be per round from Reduce and from LocalPredict, meaning PredictionSort's query complexity is balanced with that of the rest of the algorithm.
Algorithm 1 FourCycleSort(V, E)
1: .
2: Maintain a set of all queried edge directions and their transitive closure.
3: .
4: while do
5: .
6: .
7: .
8: .
9: .
10: Resolve all edges of that disagree with and add all other verified predictions.
11: return PredictionSort(V, E, Q, ).
Now, we examine what happens in each round of Reduce (Algorithm 2). In Section 2, we describe the main idea behind our algorithm, which involves looking for edges that are contained in many four-cycles, then looking for inversions among such edges, and certifying many edges when these inversions are found. However, the overview given assumes a regularity condition that the degree of every vertex is at most for . We cannot assume this in general, but we can get the same benefits from splitting the vertices of our graph into buckets based on their degrees. Then, within each bucket, we can assume that the degrees of each vertex are upper-bounded by the threshold of that bucket. The purpose of Reduce is to give an initial prediction for the edge directions with LocalPredict, then create these buckets so that they can be processed individually.
The bucketing works as follows. We first split vertices into buckets for such that if where is the degree of among edges in and .
Then, an edge is placed in bucket if and . Also, let the size of each vertex bucket be , and let the size of each edge bucket be .
Once these buckets are created, we loop through them and process each one individually with ProcessBucket, then collect all peeled and deferred edges from each bucket and return them.
Algorithm 2 Reduce(V, E, Q, E', r)
1: for . 2: . 3: Update by removing resolved edges in .
4: // Create vertex buckets. 5: for . 6: Put in when for . 7: // Create edge buckets for based on starting and ending vertex. 8: for . 9: Put in when for .
10: . 11: for do 12: . 13: . 14: return .
5 Expanding inverted witnesses
Before discussing the ProcessBucket algorithm, we will describe and prove an important fact about a common subroutine ExpandWitness. To do this, we first define our main four-cycle gadget that we use to verify a large number of edge directions from a relatively small number of queried edges. The gadget consists of a cycle on four vertices where the predicted edge directions are . We call an instance of this gadget in our graph a witness. Also, for a given edge in some subset of predicted edges , we define as the number of witnesses containing consisting entirely of edges in . In other words,
Our gadget becomes useful upon finding an inversion in one of the edges. Since the gadget is symmetric, let there be an inversion between and making the true direction . In this case, if we query edges and and determine that they were predicted correctly, then by transitivity we also confirm the edge . See Figure 2.1.
We make the best use of this inferred edge direction in the case where there is a single edge that is contained in a large number of witnesses. If we find an inversion in this case, then by querying every edge adjacent to and , we will end up inferring the “opposite edge” for each witness that had both of its “side edges” confirmed. In addition, from Lemma 1, we can be sure that many of the witnesses containing have correct predictions, so all that is required is to pick a proper threshold of witnesses containing edge where it is worth it to expand in this way. The subroutine
ExpandWitness is given an edge-bucket , an edge , and the assumption both that and that we have found an inversion at so that its true direction is .
Algorithm 3 ExpandWitness(V, E, Q, )
1: Let e be predicted but with true direction .
2: Query all edges in adjacent to u or v.
3: Update Q.
We define this threshold differently for each edge bucket being processed. For each , we define . We use this threshold to prove the following lemma.
Lemma 4. Given a graph , a set of known edge directions , a subset of unknown edges with predicted direction given by ProcessBucket (Algorithm 5), and parameter . There exists a subroutine ExpandWitness (Algorithm 3) that, when called on inverted edge with , verifies the direction of at least edges in with at most queries. Furthermore, the total query cost of all calls to ExpandWitness for a given call to ProcessBucket is at most .
Proof. Consider that we find an inversion at edge where . We then query all unknown edges in adjacent to both and , making at most queries. From Lemma 1, we know that at most predictions adjacent to are wrong. Each of these can affect at most witnesses. Similarly, at most predictions adjacent to are wrong, and each of these can affect at most witnesses. Thus, at most witnesses are affected by inversions on “side edges”. Therefore, at least witnesses are confirmed, so we verify the direction of at least edges from at most queries, proving the first part of the claim.
The second part of the claim is about the total query complexity of expanding all witnesses. To do this, we first consider the query complexity of all witness expansions of edges in . Each expansion will cost us at most queries, but will resolve at least edges. Without loss of generality, assume that ; then a simple upper bound for the size of is . Thus, because each edge can be resolved at most once, the total queries of all expansions in is
6 Existence of many witnesses in the core
Now that we have shown that finding an inversion on an edge contained in many witnesses allows us to verify a large number of edges with a relatively small number of queries, we explain exactly when and how this is used during the ProcessBucket algorithm.
The algorithm is given the structure of the graph and the known information about queried edges, as well as a bucket of edges and a sampling parameter r. The goal is to efficiently find inversions among edges that are contained in more witnesses than the bucket's threshold . To do this, we start with a process Peel which takes in the set of edges in with unknown direction, denoted , and the threshold . The process then works by peeling off edges, one by one, that are contained in fewer than witnesses. These peeled edges get added to a set , and the “core” of edges that remain is also returned. This process takes no queries and runs in polynomial time. We will show later that, over all buckets, the number of peeled edges is small.
Algorithm 4 Peel(V, E, Q, )
1: .
2: while there is an edge with do
3: // If below the threshold, remove from and add it to .
4: , .
5: return .
Once edges have been peeled, finding any inversion in the core quickly will help us verify a substantial number of edges by running ExpandWitness on that edge as described in Section 5. Furthermore, ExpandWitness will spend queries for any edge in bucket , so we can afford to spend queries looking for each inversion, and the number of queries needed will only increase by an factor. The algorithm, therefore, randomly samples edges in the core and looks for an inversion. If it finds one, it calls ExpandWitness and repeats the process, including the peeling. If it does not find one, then we ensure that the number of incorrect predictions among unresolved edges must be small, so we defer them to be resolved during PredictionSort.
Algorithm 5 ProcessBucket(V, E, Q, )
1: .
2: while there remain unresolved, underferred, and unpeeled edges in do
3: all currently unresolved edges in .
4: .
5: Query edges in uniformly at random (or all of them if ).
6: if inversion found at edge then
7: ExpandWitness(V, E, Q, ).
8: else
9: all unresolved edges in .
10: return .
11: return .
We now must prove three bounds about Peel and ProcessBucket, namely a bound on the number of queries, a bound on the number of peeled edges, and a bound on the number of incorrect predictions among deferred edges. To start, the query complexity is easy because we already proved, in Lemma 4, that the total number of queries of all calls to ExpandWitness for a given call to ProcessBucket is at most . Thus, since we lose an factor querying to find these inversions in comparison to the cost of expanding them, the total query complexity of a single call to ProcessBucket is at most . Summing over all edge buckets gives . Thus, the query complexity for a single call to Reduce is at most .
Lemma 5. Given a graph , a set of known edge directions , a subset of predicted edges given by Reduce (Algorithm 2), and a threshold . Let be the fixed number of edges in the bucket before any call to ProcessBucket. There is a polynomial-time algorithm Peel (Algorithm 4) that, without querying the graph, finds a core of edges , such that every edge has . In addition, all other edges in are either verified or peeled in such that
Proof. Examining Algorithm 4, we see that if there is any edge with , we peel it from and put it in . Thus, at the end of the algorithm, all edges in have . We call the final state of our core and need only prove that it has at least edges. To do this, we first prove a claim giving a lower bound on the number of four-cycles in bipartite graphs. This claim is a corollary and special case of a lemma by [PM84, Lemma 1]. We give a full proof here.
Claim 1 (Corollary of Lemma 1 in [PM84]). Given a bipartite graph with vertices and edges, denote the number of distinct four-cycles . It holds that
Proof. Let the left and right sets be and with . For each unordered pair on the left , let be the number of common neighbors between them in , and let be the sum of these for all unordered pairs . In other words
Now, this sum counts the number of common neighbors between two distinct vertices in . This is equivalent to the number of paths of length 2 from to and back to . We re-evaluate this sum by counting from the right side. Each vertex contributes to exactly such paths. Thus we also have
Expanding and using the Cauchy-Schwarz (Proposition 1) inequality to show that gives
(1)
Now we count four-cycles. Each four-cycle is defined by two distinct paths of length two, as counted above, with common start and endpoints. Thus, each pair of vertices contributes exactly four-cycles. Thus, the total number of four-cycles is
Again expanding and using Cauchy-Schwarz (Proposition 1) to see that gives
Where the last line uses both the fact that and from (1). This proves Claim 1.
With this, we continue the proof of Lemma 5. We wish to show that the number of edges in the core is large, so we show that the number of edges peeled must be small. To do this, we count the number of witnesses in and denote this as . We use a charging argument: for each witness in , charge it to the first edge that was peeled. For any witness, at the point that its first edge is peeled, all edges remain in . We also know that when we peel edge , we have . These are the only witnesses that can be charged to edge . Since this is true for every edge in ,
Now, take and construct the following bipartite graph . For each vertex , make two copies and . Then, for each edge , create an undirected edge between and . This new graph is a subgraph of with the same number of edges . Furthermore, each witness in consists of edges , which get mapped to . In the bipartite graph, this is a four-cycle. Conversely, any four-cycle in corresponds to a witness in . Thus, the number of four-cycles in is equal to the number of witnesses in . From Claim 1, if , then there are at least four cycles, so
Combining this with (2) gives
(3)
Taking a cube root gives the first term in the bound in Lemma 5, the second comes from the fact that the bound in (3) only holds when . Thus, since is upper-bounded in both cases, it is always upper-bounded by their sum, proving Lemma 5.
Next, we prove that, in total, few edges are peeled.
Lemma 6. Given a graph , a set of known edge directions Q, a set of vertex buckets of size and edge buckets of size for given by Reduce (Algorithm 2), and a parameter , the total number of edges peeled across all buckets is at most .
Proof. This proof is just collecting terms and applying some standard combinatorial inequalities. The total number of peeled edges is equal to the sum of the sizes of all . We have
We bound the terms individually. First, we see that
where we use both Proposition 2 to show that and the fact that . Next, we bound the first term as follows.
We now bound the internal sum.
Claim 2. It holds that
Proof. To prove this, we split the sum into two parts and apply Hölder's inequality (Proposition 3) to each. We set the threshold . In the first case, we use Hölder's with p = 3 and q = 3/2.
In the second case, where , we instead split the sequences differently but use the same and for Hölder's.
The first term is a geometrically decreasing sequence with ratio , so the sum is at most . For the second term, we see that if then and . Therefore, we can rearrange our sum as
Plugging both of these bounds back into (7) gives
Lastly, combining this with (6) proves Claim 2.
We continue with the proof of Lemma 6 and substitute Claim 2 into (5) giving
Lastly, substituting and combining with (4) gives
Now that we have shown that the total number of peeled edges is small, it remains to show that among deferred edges, there are few incorrect predictions.
Lemma 7. Given a graph , a set of known edge directions , a subset of predicted edges given by Reduce (Algorithm 2), and a parameter , let . At the end of ProcessBucket(V, E, Q, , with probability the number of incorrectly predicted edge directions among deferred edges is at most
Proof. Assume that there are more than incorrect predictions among edges in after peeling. We sample edges in at random, and if no inversion is found, we defer these edges. Since there are at least incorrect predictions among at most edges, the probability of finding one from a random sample is at least . Thus, the probability of missing after samples is at most
If we do find an inversion, however, we expand witnesses and repeat the process. Crudely, for each call to ProcessBucket this can happen no more than times, as each time we verify at least one edge. Thus, by union bound, upon terminating the algorithm we must have fewer than incorrect predictions with probability , proving the claim.
Lastly, we must bound the number of errors over all buckets.
Lemma 8. Given a graph , a set of known edge directions , a set of vertex buckets of size and edge buckets of size for given by Reduce (Algorithm 2), and a parameter , with probability , the number of incorrectly predicted edge directions among all deferred edges in in a given call to Reduce is at most
Proof. From Lemma 7, we know that the number of incorrect edges in each bucket is at most with probability each. By union bound, this is true of all buckets with probability at least . Conditioning on this and summing over all buckets gives
The third inequality charges each edge in to its endpoint in , and the last inequality uses the fact that for , .
We are now ready to prove Lemma 3.
Proof of Lemma 3. The proof follows from the combination of Lemma 6, Lemma 8, the proved query complexity of , and the failure probability of . These, together, show the guarantees we need for Reduce in Lemma 3.²
7 Final algorithm and query bound
Lemma 9 (Full version of Theorem 1). Given an -vertex undirected graph with hidden edge directions forming a DAG with a Hamiltonian path, there exists a randomized algorithm FourCycleSort(V,E) that determines, in polynomial time and with probability , the direction of every edge with edge queries.
Proof. First, by Lemma 6, each call to Reduce peels fewer than half of the edges it receives. Since these peeled edges become the next edges passed in as , Reduce is called no more than times. Furthermore, each call to Reduce costs us queries, and, from Lemma 8, defers a set of edges with no more than incorrect predictions and with probability . Lastly, we have an additional failure probability of from the call to LocalPredict.
For each call to Reduce, we set , since each time decreases by a factor of at least two (geometrically) and never goes below , the sum of these over all calls to Reduce is at most . Therefore, the total number of queries over all calls to Reduce is . In addition, totaling up incorrect predictions gives total errors and a probability of at least .
Next, by Lemma 1, the call to LocalPredict on an edge set with and parameter returns a set of predicted edges using queries and failure probability . This set has the guarantee that, for each vertex , there are at most incorrectly predicted edges adjacent to . Summing over vertices, this gives at most incorrectly predicted edges in total.
Lastly, combining the predictions from and and running PredictionSort discovers the direction of every edge in the graph in total queries with failure probability . Setting as in the algorithm balances this tradeoff and gives our algorithm a query complexity of and failure probability for , proving Theorem 1.
Acknowledgments
The first author thanks Moses Charikar for first introducing him to the generalized sorting problem and for many insightful conversations. We also thank Amir Azarmehr, Alma Ghafari, and Mohammad Saneian for helpful discussions over the years.
²The failure probability comes from the in Lemma 8 and the from the single call to LocalPredict.
The overall approach of this paper was developed by the authors, independent of AI. However GPT-6 Astra was used in formalizing and optimizing the final bound. With no human guidance, GPT-6 Astra was not able to break the bound of [HKK11] after working for 50+ hours. The authors wrote the entire paper and assume full responsibility for its content.
References
[ABF96] Noga Alon, Phillip G. Bradford, and Rudolf Fleischer. "Matching Nuts and Bolts Faster". In: Information Processing Letters 59.3 (1996), pp. 123–127. DOI: 10.1016/0020-0190(96)00104-4. URL: https://doi.org/10.1016/0020-0190(96)00104-4.
[ACK19] Sepehr Assadi, Yu Chen, and Sanjeev Khanna. "Sublinear Algorithms for () Vertex Coloring". In: SODA. 2019, pp. 767–786. DOI: 10.1137/1.9781611975482.48. URL: https://doi.org/10.1137/1.9781611975482.48.
[Ail+04] Nir Ailon et al. "Estimating the Distance to a Monotone Function". In: AP-PROX/RANDOM. Vol. 3122. Lecture Notes in Computer Science. 2004, pp. 229–236. DOI: 10.1007/978-3-540-27821-4_21. URL: https://doi.org/10.1007/978-3-540-27821-4_21.
[Alo+94] Noga Alon et al. "Matching Nuts and Bolts". In: SODA. 1994, pp. 690–696. URL: https://web.cs.ucla.edu/~rafail/PUBLIC/17.pdf.
[Bel18] Aleksandrs Belovs. "Adaptive Lower Bound for Testing Monotonicity on the Line". In: APPROX/RANDOM. Vol. 116. LIPIcs. 2018, 31:1–31:10. DOI: 10.4230/LIPIcs.APPROX-RANDOM.2018.31. URL: https://doi.org/10.4230/LIPIcs.APPROX-RANDOM.2018.31.
[BF95] Phillip G. Bradford and Rudolf Fleischer. "Matching Nuts and Bolts Faster". In: ISAAC. Vol. 1004. Lecture Notes in Computer Science. 1995, pp. 402–408. DOI: 10.1007/BFb0015446. URL: https://doi.org/10.1007/BFb0015446.
[Bra95] Phillip G. Bradford. "Matching Nuts and Bolts Optimally". In: MPI-I-95-1-025 (1995). Technical report. URL: https://pure.mpg.de/pubman/item/item_1832264_4/component/file_1857924/MPI-I-95-1-025.pdf.
[Cha+00] Moses Charikar et al. "Query Strategies for Priced Information (Extended Abstract)". In: STOC. 2000, pp. 582–591. DOI: 10.1145/335305.335382. URL: https://doi.org/10.1145/335305.335382.
[CK12] Andrew M. Childs and Robin Kothari. "Quantum Query Complexity of Minor-Closed Graph Properties". In: SIAM Journal on Computing 41.6 (2012), pp. 1426–1450. DOI: 10.1137/110833026. URL: https://doi.org/10.1137/110833026.
[Dür+06] Christoph Dürr et al. "Quantum Query Complexity of Some Graph Problems". In: SIAM Journal on Computing 35.6 (2006), pp. 1310–1328. DOI: 10.1137/050644719. URL: https://doi.org/10.1137/050644719.
[Erg+98] Funda Ergün et al. "Spot-Checkers". In: STOC. 1998, pp. 259–268. DOI: 10.1145/276698.276757. URL: https://doi.org/10.1145/276698.276757.
[Fis+02] Eldar Fischer et al. "Monotonicity Testing over General Poset Domains". In: STOC. 2002, pp. 474–483. DOI: 10.1145/509907.509977. URL: https://doi.org/10.1145/509907.509977.
[Fis04] Eldar Fischer. "On the Strength of Comparisons in Property Testing". In: Information and Computation 189.1 (2004), pp. 107–116. DOI: 10.1016/j.ic.2003.09.003. URL: https://doi.org/10.1016/j.ic.2003.09.003.
[FM08] Eldar Fischer and Arie Matsiah. "Testing Graph Isomorphism". In: SIAM Journal on Computing 38.1 (2008), pp. 207–225. DOI: 10.1137/070680795. URL: https://doi.org/10.1137/070680795.
[GK01] Anupam Gupta and Amit Kumar. "Sorting and Selection with Structured Costs". In: FOCS. 2001. URL: https://cs.nyu.edu/~anupamg/papers/focs01b.pdf.
[HKK11] Zhiyi Huang, Sampath Kannan, and Sanjeev Khanna. "Algorithms for the Generalized Sorting Problem". In: FOCS. 2011. URL: https://www.cis.upenn.edu/~sanjeev/papers/focs11_sorting.pdf.
[Jia+24] Shaofeng H.-C. Jiang et al. "Algorithms for the Generalized Poset Sorting Problem". In: ICALP. 2024. URL: https://arxiv.org/abs/2304.01623.
[KK03] Sampath Kannan and Sanjeev Khanna. "Selection with Monotone Comparison Costs". In: SODA. 2003, pp. 10–17.
[KMS98] János Komlós, Yuan Ma, and Endre Szemerédi. "Matching Nuts and Bolts in Time". In: SIAM Journal on Discrete Mathematics 11.3 (1998), pp. 347–372. DOI: 10.1137/S0895480196304982. URL: https://doi.org/10.1137/S0895480196304982.
[KN21] William Kuszmaul and Shyam Narayanan. "Stochastic and Worst-Case Generalized Sorting Revisited". In: FOCS. 2021. URL: https://arxiv.org/abs/2111.07222.
[Lu+21] Pinyan Lu et al. "Generalized Sorting with Predictions". In: SOSA. 2021. URL: https://arxiv.org/abs/2011.00172.
[PM84] P. Erdős and M. Simonovits. "Cube-supersaturated graphs and related problems". In: Progress in Graph Theory. Ed. by J. A. Bondy and U. S. R. Murty. Toronto: Academic Press, 1984, pp. 203–218.
[PRR06] Michal Parnas, Dana Ron, and Ronitt Rubinfeld. "Tolerant Property Testing and Distance Approximation". In: Journal of Computer and System Sciences 72.6 (2006), pp. 1012–1042. DOI: 10.1016/j.jcss.2006.03.002. URL: https://doi.org/10.1016/j.jcss.2006.03.002.
[Ras16] Sofya Raskhodnikova. "Testing if an Array Is Sorted". In: Encyclopedia of Algorithms. Springer, 2016, pp. 2219–2222. DOI: 10.1007/978-1-4939-2864-4_700. URL: https://doi.org/10.1007/978-1-4939-2864-4_700.
[Raw92] Gregory J. E. Rawlins. Compared to What? An Introduction to the Analysis of Algorithms. Computer Science Press, 1992.
[Ron25] Dana Ron. "Let's Try to Be More Tolerant: On Tolerant Property Testing and Distance Approximation". In: ICALP. Vol. 334. LIPIcs. 2025, 2:1–2:10. DOI: 10.4230/LIPIcs.ICALP.2025.2. URL: https://doi.org/10.4230/LIPIcs.ICALP.2025.2.
[SS10] Michael Saks and C. Seshadhri. "Estimating the Longest Increasing Sequence in Poly-logarithmic Time". In: FOCS. 2010, pp. 458–467. DOI: 10.1109/FOCS.2010.51. URL: https://doi.org/10.1109/FOCS.2010.51.
[Yos26] Yuichi Yoshida. Testing Monotonicity of Real-Valued Functions on DAGs. 2026. arXiv:2602.15341. URL: https://arxiv.org/abs/2602.15341.
A Useful Inequalities
Proposition 1 (Cauchy-Schwarz). For real numbers with sum , it holds that
Proposition 2. For nonnegative real numbers with sum , it holds that
Proof. To prove this, we use the Cauchy-Schwarz inequality (Proposition 1) on the sequence to see that
Proposition 3 (Hölder's Inequality). For positive sequences , and exponents with , it holds that
Proposition 4. For positive with , it holds that
Proof. This comes from the standard inequality and simply plugging in .
B LocalPredict algorithm and analysis
In this section we give a full description of the LocalPredict algorithm and a proof of Lemma 1. We again emphasize that this is only a small modification to an existing algorithm from [Jia+24, Lemma 5.1] and claim no novelty.
Proof of Lemma 1. To prove this, we first use a claim from [HKK11, Lemma 3.2] as a black box. The claim gives a polynomial-time algorithm that makes no queries and predicts the direction of every edge in the graph. The claim guarantees that if an ordering of the vertices that does not contradict the already-known information about queried edges is selected uniformly at random, then for each edge, the probability that edge prediction agrees with the selected ordering is at least a constant. If we do not care about running time, a simple algorithm that does this is one that, for each edge , counts the number of permutations that agree with where comes before and the number where comes before and predicts the edge direction that occurs more often.
The advantage of an algorithm of this type is that it can be wrong at most times, adaptively. Each time we query an edge and the true direction does not match the prediction, the number of possible permutations that do not contradict goes down by a constant factor. This happens at most times, assuming we recompute the predictions each time. We give the claim implied by the polynomial-time algorithm of [HKK11] and take it as a black box.
Claim 3. Given an undirected graph with a hidden underlying DAG, and a set of known edge directions , let be the set of permutations of that do not contradict . i.e. for all and , we have . Then, let be the probability that if is selected from uniformly at random. There is a randomized polynomial-time algorithm that makes no queries to the graph and, with probability for any constant , assigns predicted directions to every edge in with the property that for every edge predicted in direction from to , we have
From this claim, we can assume the existence of an algorithm that, with probability , returns a set of predicted edge directions with the property that if edge , then . Once we have this, each time we find an inverted edge with true direction , once we add that to we have reduced the size of by a constant factor of . Thus, since , we know that this can happen at most times. For implementation purposes, we also add a parameter such that does not give a prediction to an uncertified edge if . This extra parameter allows us to defer and ignore sets of unknown edges, which will become important later.
We now present the algorithm . The algorithm works by looping through each vertex and running on the graph, then randomly sampling uncertified edges adjacent to uniformly at random. If an inversion is found, we repeat. If no inversion is found, then we fix the prediction for all edges adjacent to in a variable . After doing this for all vertices , we may have some edges whose predictions contradict one another. What we then do is attempt to make a global prediction that sufficiently agrees with every individual . We make this global prediction the same way as before, by running . Then, we look for a vertex that disagrees with our global prediction by too much. In this case, since we know that is accurate, most of these errors must be in our global prediction, so we can simply sample them at random and we will find an inversion quickly with high probability. We can then repeat this until our global prediction agrees sufficiently with each . After this, can have error per vertex at most equal to the sum of the error of and the disagreement between and .
We begin by analyzing the query complexity. First, we see that for each vertex, we use queries per round to find . Split these queries into cases where we find an inversion and cases where we don't. If we find an inversion, then we can do so at most times for a total of queries. If we do not find an inversion, we fix the prediction , and this can happen at most once per vertex for a total of queries.
For the query complexity of the while loop, we only make queries per round, and each time, we either find an inversion or fail. In the case that we don't fail, this can again happen at most times for a total of . Overall, we use queries.
³The original algorithm gives a probability of , but we can boost this to for any constant by simply re-running the algorithm times and voting.
Algorithm 6 LocalPredict(V, E, Q, E', r)
1: for all .
2: for do
3: while not set or inversion found do
4: .
5: all edges in adjacent to .
6: Randomly sample uncertified edges of adjacent to and query them.
7: Update .
8: while There is some where disagrees with at least times do
9: .
10: // Let be the degree of among unverified edges in , fixed at the start of the algorithm.
11: if disagrees with at least times for some then
12: Randomly sample such edges and query them.
13: Update .
14: if no inversion found then
15: return FAIL.
16: return .
Next we prove the claim that, with high probability, every is accurate.
Claim 4. Given a graph , a set of known edge directions , a set of unknown edge directions , and a parameter . After running LocalPredict(V, E, Q, E', r), with probability , for each vertex we have
where is the number of incorrectly predicted edges in .
Proof. We start by examining a single prediction attempt on a single vertex. We sample edges uniformly at random, and if there are more than incorrectly predicted edges out of a maximum of uncertified edges, then each sample finds an inversion with probability at least , so the probability of finding none is at most
where we make use of the basic fact of Proposition 4. In total, this subroutine can happen at most times, so by union bound, the probability that we always find an inversion when there are at least is at least . Thus, for each , if we condition on this high-probability event, we can be sure that each has at most errors, proving Claim 4.
Now that we have accurate for each , we must verify that the global prediction works as intended. First, in the case where disagrees with by at most for every , we simply return , and each vertex has error at most . Assume there is some where this is not the case, so we have at least disagreements. Each such disagreement between and causes at least one of them to be wrong, but we know that is wrong at most times. Thus, is wrong in the majority of these disagreements. If we sample such disagreements, then the probability that we find none where is wrong is at most
Thus, by a union bound over possible predictions for , we fail with probability at most .
Combining this with Claim 4, we see that LocalPredict finds a prediction for which each vertex has error at most , and uses queries. Furthermore, the probability of failure is plus an additional for each call to Predict. Simply taking gives a failure probability at most over a union bound to all calls to Predict. This gives a total failure probability of , proving Lemma 1.