Algorithm Search⌘K

Algorithmintro

Borda count

Also called Borda method.

Gives each item points by its position in each input ranking and sorts the items by the total of their points.

Time
O(n k + n log n) worst
Space
O(n) extra
Where
k = the number of lists; n = the number of distinct items in the input lists
Properties
not comparison baseddeterministiciterative
Origin
Jean Charles de Borda, 1784

The Borda count merges several rankings of the same items into one. Each ranking gives points to the items by their positions, the top item gets the most, and the merged ranking sorts the items by their total points. Jean-Charles de Borda proposed it in the 18th century for elections, where each voter ranks the candidates. In information retrieval it is a standard method of rank aggregation, often called Borda-fuse, that merges the result lists of several search systems using only the ranks, not the scores.

In plain words

Several voters each put the same candidates in order. In each order, the last candidate gets 1 point, the one above it gets 2, and so on up to the top candidate. Add up the points that each candidate gets from all voters, and sort the candidates by their totals. A search system that returns only its top results is a voter who did not rank everyone. The candidates that it left out share the points of the empty places equally, so every voter gives out the same number of points. The total also counts something easy to explain: how many of the head-to-head contests a candidate wins, summed over all voters. The method is fast and fair to each voter, but it can elect a candidate other than the one that a majority prefers to each rival.

The problem

The input is kk ranked lists L1,…,LkL_1, \ldots, L_k. Each list holds distinct items, best first, and it may be partial. Let UU be the union of the items and n=∣U∣n = |U|. For a list LL that holds xx, L(x)L(x) is the rank of xx in LL, from 1. The output is one ranking of all of UU. No scores are given, and the lists may hold different items, as is usual for the top results of different search engines.

The algorithm

  1. BORDA(L1, ..., Lk)
  2. 1U ← the union of the items of L1, ..., Lk; n ← |U|
  3. 2s(x) ← 0 for each x in U
  4. 3for each list L:
  5. 4for i ← 1 to |L|: s(L[i]) ← s(L[i]) + (n - i + 1)
  6. 5for each x in U not in L: s(x) ← s(x) + (n - |L| + 1) / 2
  7. 6return U sorted by s, highest first, ties to the smaller item

Line L4 gives nn points to the top of each list, n−1n - 1 to the second, and so on. Line L5 handles partial lists: the ranks ∣L∣+1|L| + 1 to nn are empty, and their points, 1+2+⋯+(n−∣L∣)1 + 2 + \cdots + (n - |L|), are shared equally by the n−∣L∣n - |L| missing items, which gives each one (n−∣L∣+1)/2(n - |L| + 1)/2. This is the rule that Borda-fuse uses. With it, every list hands out exactly n(n+1)/2n(n+1)/2 points, full or not. The code keeps the scores as exact fractions, because the half points of line L5 must not cause rounding errors in the tie test of line L6.

Example

Take the two runs of the toy collection for the query "sorted array search": the BM25 list A=1,2,8,7,4A = 1, 2, 8, 7, 4 and a second list B=1,6,8,2,4B = 1, 6, 8, 2, 4. The union is {1,2,4,6,7,8}\{1, 2, 4, 6, 7, 8\}, so n=6n = 6. Each list holds 5 items and misses one, which gets (6−5+1)/2=1(6 - 5 + 1)/2 = 1 point. The table shows the scores after each pass of line L3.

document 1 2 8 6 7 4
points from AA 6 5 4 1 (missing) 3 2
score after AA 6 5 4 1 3 2
points from BB 6 3 4 5 1 (missing) 2
score after BB 12 8 8 6 4 4

Line L6 returns 1,2,8,6,4,71, 2, 8, 6, 4, 7. Documents 2 and 8 tie at 8 points and documents 4 and 7 tie at 4, so the tie rule decides those places. Ties like these are common with few lists.

Now take three candidates and five voters: three ballots say a,b,ca, b, c and two say b,c,ab, c, a. The scores are a=3⋅3+2⋅1=11a = 3 \cdot 3 + 2 \cdot 1 = 11, b=3⋅2+2⋅3=12b = 3 \cdot 2 + 2 \cdot 3 = 12 and c=3⋅1+2⋅2=7c = 3 \cdot 1 + 2 \cdot 2 = 7, so Borda elects bb. Yet aa beats bb on 3 of the 5 ballots and beats cc on 3 of 5: aa is the Condorcet winner, the candidate that a majority prefers to each rival. Borda adds margins, and bb's large lead over cc (5 to 0) outweighs its small loss to aa. The Kemeny ranking of this profile is a,b,ca, b, c, with total Kendall tau distance 4, while the Borda order b,a,cb, a, c has distance 5.

Correctness

Lines L1 to L5 compute s(x)=∑lpl(x)s(x) = \sum_l p_l(x), where pl(x)p_l(x) is n−Ll(x)+1n - L_l(x) + 1 when LlL_l holds xx and (n−∣Ll∣+1)/2(n - |L_l| + 1)/2 when it does not, and line L6 sorts by ss. The file proofs/correctness.md proves what this score means. Extend each list by putting its missing items below its listed items, tied with each other. Then s(x)s(x) is kk plus the number of items that xx beats, summed over the lists, with a tie worth half. For full lists, every order by decreasing ss minimizes the sum over the lists of ∑x(σ(x)−L(x))2\sum_x (\sigma(x) - L(x))^2, the squared distance between rank positions; the proof expands the square and uses an exchange argument.

For the Kemeny objective there is a proved bound that the code inherits. Coppersmith, Fleischer and Rudra prove that, on full lists, the Borda order has a total Kendall tau distance at most 5 times the minimum. The tests check this by brute force over all permutations of up to 6 items. On those random profiles the worst ratio was below 2; that is a measurement on small random inputs, not a bound.

Proof: The Borda score counts pairwise wins, and the Borda order minimizes the squared rank distancefull

Let L1,…,LkL_1, \ldots, L_k be the input lists. Each holds distinct items, best first, and may be partial. Let UU be the union of their items and n=∣U∣n = |U|. For a list LL and an item x∈Lx \in L, L(x)L(x) is the rank of xx in LL, from 1. Lines L1 to L5 give each item xx the score

s(x)=∑l=1kpl(x),pl(x)={n−Ll(x)+1if x∈Ll,(n−∣Ll∣+1)/2if x∉Ll.s(x) = \sum_{l=1}^{k} p_l(x), \qquad p_l(x) = \begin{cases} n - L_l(x) + 1 & \text{if } x \in L_l, \\ (n - |L_l| + 1)/2 & \text{if } x \notin L_l. \end{cases}

Line L4 adds the first case, line L5 adds the second, and line L2 starts each sum at 0, so the code computes exactly ss. Line L6 sorts by ss, high first, with ties broken by the item. What remains is to say what ss measures.

Lemma 1 (fair share). If LL misses m=n−∣L∣≥1m = n - |L| \ge 1 items, the ranks ∣L∣+1,…,n|L| + 1, \ldots, n carry ∑i=∣L∣+1n(n−i+1)=m(m+1)/2\sum_{i = |L| + 1}^{n} (n - i + 1) = m (m + 1)/2 points, and each missing item gets m(m+1)/(2m)=(m+1)/2=(n−∣L∣+1)/2m(m+1)/(2m) = (m + 1)/2 = (n - |L| + 1)/2. So every list hands out 1+2+⋯+n=n(n+1)/21 + 2 + \cdots + n = n(n+1)/2 points in total, whether it is full or partial. □\square

Theorem 1 (pairwise form). Extend each list LL to a weak order on UU by putting every missing item below every item of LL, with the missing items tied with each other. For x∈Ux \in U let wL(x)w_L(x) be the number of items y≠xy \ne x that this weak order puts strictly below xx, and tL(x)t_L(x) the number of items y≠xy \ne x tied with xx. Then pL(x)=1+wL(x)+12tL(x)p_L(x) = 1 + w_L(x) + \tfrac12 t_L(x), and so

s(x)=k+∑l=1k(wLl(x)+12tLl(x)).s(x) = k + \sum_{l=1}^{k} \left( w_{L_l}(x) + \tfrac12 t_{L_l}(x) \right).

Proof. If x∈Lx \in L at rank ii, the items below xx are the ∣L∣−i|L| - i items of LL after xx and the n−∣L∣n - |L| missing items, so wL(x)=n−iw_L(x) = n - i, tL(x)=0t_L(x) = 0 and 1+wL(x)=n−i+1=pL(x)1 + w_L(x) = n - i + 1 = p_L(x). If x∉Lx \notin L, no item is below xx, the other n−∣L∣−1n - |L| - 1 missing items are tied with it, and 1+12(n−∣L∣−1)=(n−∣L∣+1)/2=pL(x)1 + \tfrac12 (n - |L| - 1) = (n - |L| + 1)/2 = p_L(x). □\square

So the Borda score is, up to the constant kk, the number of pairwise contests that xx wins over all lists, with a tie worth half a win. This is why Borda is a positional method and a pairwise method at the same time, and why it can disagree with the majority relation: it adds up the margins over all pairs, and a large win against one item can outweigh a small loss against another.

Theorem 2 (squared rank distance). Let all lists be full rankings of UU, so each LlL_l is a bijection from UU to {1,…,n}\{1, \ldots, n\}. For a ranking σ\sigma of UU let D(σ)=∑l=1k∑x∈U(σ(x)−Ll(x))2D(\sigma) = \sum_{l=1}^{k} \sum_{x \in U} (\sigma(x) - L_l(x))^2. Every order that line L6 can return minimizes DD, and so does every other order that sorts the items by decreasing ss.

Proof. Let R(x)=∑lLl(x)R(x) = \sum_l L_l(x) be the total rank of xx. For full lists s(x)=∑l(n+1−Ll(x))=k(n+1)−R(x)s(x) = \sum_l (n + 1 - L_l(x)) = k(n+1) - R(x), so sorting by decreasing ss is sorting by increasing RR. Expand the square:

D(σ)=k∑xσ(x)2+∑l∑xLl(x)2−2∑xσ(x)R(x).D(\sigma) = k \sum_{x} \sigma(x)^2 + \sum_{l} \sum_{x} L_l(x)^2 - 2 \sum_{x} \sigma(x) R(x).

The first term is k(12+⋯+n2)k(1^2 + \cdots + n^2) for every permutation σ\sigma, and the second does not depend on σ\sigma. So σ\sigma minimizes DD exactly when it maximizes F(σ)=∑xσ(x)R(x)F(\sigma) = \sum_x \sigma(x) R(x).

Suppose σ(x)<σ(y)\sigma(x) < \sigma(y) and R(x)>R(y)R(x) > R(y). Let σ′\sigma' be σ\sigma with the positions of xx and yy exchanged. Then F(σ′)−F(σ)=σ(y)R(x)+σ(x)R(y)−σ(x)R(x)−σ(y)R(y)=(σ(y)−σ(x))(R(x)−R(y))>0F(\sigma') - F(\sigma) = \sigma(y) R(x) + \sigma(x) R(y) - \sigma(x) R(x) - \sigma(y) R(y) = (\sigma(y) - \sigma(x))(R(x) - R(y)) > 0. So a maximizer of FF, which exists because there are finitely many permutations, has no such pair: it lists the items by increasing RR. Any two orders by increasing RR differ only inside groups of equal RR, and exchanging two items with equal RR does not change FF. So all orders by increasing RR have the same value of FF, one of them is a maximizer, and hence all of them are. □\square

Remark (cited, not proved here). For full lists, Coppersmith, Fleischer and Rudra (ACM Transactions on Algorithms 6(3), Article 55, 2010) prove that the order by Borda score has a total Kendall tau distance to the lists at most 5 times the minimum, the Kemeny cost. The test file checks this bound by brute force over all permutations of up to 6 items. It is a property of the order, not of the code, so it needs no separate argument about lines L1 to L6.

The tests in impl/python/test_borda_count.py check the formula for ss, Lemma 1, Theorem 1 with the weak-order extension, Theorem 2 by brute force, and the factor 5.

Complexity

Line L4 runs once for each entry of each list and line L5 once for each missing pair of an item and a list, so lines L3 to L5 take Θ(nk)\Theta(n k) time with a hash map for the scores. Line L6 sorts nn items in O(nlog⁡n)O(n \log n). The total is O(nk+nlog⁡n)O(n k + n \log n) time, and the extra space is O(n)O(n) for the scores and the set of items of the current list. If only the listed items are needed, line L5 can add the shares lazily: keep one running total of the shares of each list and subtract the shares of the listed items, which brings the time to O(∑l∣Ll∣+nlog⁡n)O(\sum_l |L_l| + n \log n).

Properties

  • Anonymous and neutral. Renaming the lists or the items does not change the result, apart from the tie rule of line L6.
  • Scores add. The score of a profile is the sum of the scores of its lists. So if two groups of lists each rank xx above yy by score, their union does too.
  • Monotone. Moving xx up one place in one list raises s(x)s(x) by 1, lowers the item that it passes by 1 and changes no other score, so xx never falls in the result.
  • Not Condorcet consistent. The five-voter profile above shows that the Borda winner need not be the Condorcet winner. On full lists Borda never puts a Condorcet loser, an item that a majority ranks below each rival, first: by the pairwise form of the score, such an item wins fewer than k/2k/2 contests against each rival, so its score is below the average score k(n+1)/2k(n+1)/2, and some other item scores more.
  • Not independent of other items. In the same profile, deleting cc leaves aa against bb, which aa wins 3 to 2. So the order of aa and bb depends on a third candidate.

Variants and improvements

  • Weighted Borda. Multiply the points of each list by a weight for its system, learned from training queries. The pairwise form still holds, with weighted counts.
  • Other position weights. Any decreasing points per rank give a positional method. The weight 1/(k+i)1/(k + i) for rank ii is reciprocal rank fusion, which gives much more weight to the top ranks than the linear Borda points do.
  • Missing items get nothing. Some systems give 0 points to missing items. Then a long list gives out more points than a short one, so the lists that return more results have more influence on the merged order.
  • Local Kemenization. Run the clean-up pass of Markov chain rank aggregation on the Borda order. It swaps neighbours that a strict majority orders the other way, and it never increases the Kendall distance. On the five-voter profile it turns b,a,cb, a, c into a,b,ca, b, c.
  • Score fusion. When the systems give comparable scores, CombSUM and CombMNZ use the scores in place of the ranks.

When to use it

Use the Borda count when you must merge ranked lists whose scores cannot be compared, the lists are short or have similar lengths, and you want a method that is simple to explain and to compute. It is a good first baseline for metasearch and for merging the votes of several rankers in an ensemble. If the top of each list matters much more than the middle, as in most web search, reciprocal rank fusion is a better default. If majorities matter, as in the five-voter example, add local Kemenization or use a pairwise method.

Pitfalls

  • Points scaled by the list length. Giving ∣L∣−i+1|L| - i + 1 points in line L4 in place of n−i+1n - i + 1 makes the top of a short list worth less than the top of a long list, so the result depends on how deep each system returned results. Use nn, the size of the union, for every list.
  • Missing items left out of the count. If line L5 is dropped, an item that a list misses gets 0 from it, while line L5 gives it the average of the empty places. With n=100n = 100 and a list of 10, that is 0 in place of 45.5, against 91 for the tenth item of the list. The two rules give different results whenever items differ in how many lists hold them, so keep line L5 or drop it on purpose, and say which.
  • Floating point halves. The share (n−∣L∣+1)/2(n - |L| + 1)/2 is a half when n−∣L∣n - |L| is even, and sums of halves in floats can split exact ties. Keep the scores as integers times 2, or as fractions, before line L6.
  • Ties decided by accident. With two lists, ties are frequent, as documents 2 and 8 show. State the tie rule of line L6, or break ties by a third signal such as the best single rank.
  • Strategic lists. A system that wants to push xx can put xx first and a strong rival last, as the ballots b,c,ab, c, a do to aa. Borda is known to be open to this kind of manipulation, so do not use it to merge lists from parties that compete.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

borda_count.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/borda-count/. The authors are listed in prov/2CGC7D.jsonl.

from fractions import Fraction
from typing import Any, Hashable, Sequence

Ranking = Sequence[Hashable]


def borda_scores(rankings: Sequence[Ranking]) -> dict[Any, Fraction]:
    """Return the Borda score of each item of the union of the rankings.

    Each ranking lists distinct items, best first, and may be partial. With n items in
    the union, the item at rank i of a list gets n - i + 1 points. The items that a list
    leaves out share the points of the ranks |L| + 1 to n equally, so each gets
    (n - |L| + 1) / 2 points from that list.
    """
    union = {x for r in rankings for x in r}  # @line L1
    n = len(union)
    score = {x: Fraction(0) for x in union}  # @line L2
    for r in rankings:  # @line L3
        for i, x in enumerate(r, start=1):
            score[x] += n - i + 1  # @line L4
        rest = Fraction(n - len(r) + 1, 2)
        listed = set(r)
        for x in union - listed:
            score[x] += rest  # @line L5
    return score


def borda(rankings: Sequence[Ranking]) -> list[Any]:
    """Return the items sorted by Borda score, high first, ties by item."""
    score = borda_scores(rankings)
    return sorted(score, key=lambda x: (-score[x], x))  # @line L6
test_borda_count.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/borda-count/. The authors are listed in prov/2CGC7D.jsonl.

import itertools
import random
from fractions import Fraction

from borda_count import borda, borda_scores


def random_profile(rng, n, k, partial):
    items = list(range(1, n + 1))
    out = []
    for _ in range(k):
        r = items[:]
        rng.shuffle(r)
        if partial:
            r = r[: rng.randint(0, n)]
        out.append(r)
    return out


def kendall(sigma, tau):
    ps = {x: i for i, x in enumerate(sigma)}
    pt = {x: i for i, x in enumerate(tau)}
    return sum(1 for x, y in itertools.combinations(sigma, 2) if (ps[x] - ps[y]) * (pt[x] - pt[y]) < 0)


def test_points_by_the_formula():
    rng = random.Random(1)
    for _ in range(300):
        prof = random_profile(rng, rng.randint(1, 7), rng.randint(1, 5), partial=True)
        union = sorted({x for r in prof for x in r})
        n = len(union)
        s = borda_scores(prof)
        assert sorted(s) == union
        for x in union:
            want = Fraction(0)
            for r in prof:
                if x in r:
                    want += n - (r.index(x) + 1) + 1
                else:
                    want += Fraction(sum(n - i + 1 for i in range(len(r) + 1, n + 1)), n - len(r))
            assert s[x] == want
        # Each list hands out 1 + 2 + ... + n points.
        assert sum(s.values()) == len(prof) * n * (n + 1) // 2


def test_score_is_one_plus_pairwise_wins_plus_half_ties():
    rng = random.Random(2)
    for _ in range(300):
        prof = random_profile(rng, rng.randint(1, 7), rng.randint(1, 5), partial=True)
        union = sorted({x for r in prof for x in r})
        s = borda_scores(prof)
        for x in union:
            want = Fraction(0)
            for r in prof:
                pos = {y: i for i, y in enumerate(r)}
                big = len(union)
                want += 1
                for y in union:
                    if y == x:
                        continue
                    px, py = pos.get(x, big), pos.get(y, big)
                    if px < py:
                        want += 1
                    elif px == py:
                        want += Fraction(1, 2)
            assert s[x] == want


def test_borda_order_minimizes_squared_rank_distance():
    rng = random.Random(3)
    for _ in range(80):
        n = rng.randint(1, 6)
        prof = random_profile(rng, n, rng.randint(1, 5), partial=False)
        items = list(range(1, n + 1))

        def cost(sigma):
            p = {x: i for i, x in enumerate(sigma)}
            return sum((p[x] - r.index(x)) ** 2 for r in prof for x in items)

        best = min(cost(p) for p in itertools.permutations(items))
        assert cost(borda(prof)) == best


def test_borda_is_a_five_approximation_of_kemeny():
    rng = random.Random(4)
    worst = Fraction(1)
    for _ in range(80):
        n = rng.randint(2, 6)
        prof = random_profile(rng, n, rng.randint(1, 6), partial=False)
        perms = list(itertools.permutations(range(1, n + 1)))
        opt = min(sum(kendall(p, r) for r in prof) for p in perms)
        got = sum(kendall(borda(prof), r) for r in prof)
        if opt == 0:
            assert got == 0
        else:
            worst = max(worst, Fraction(got, opt))
            assert got <= 5 * opt
    assert worst < 2


def test_condorcet_failure():
    prof = [list("abc")] * 3 + [list("bca")] * 2
    s = borda_scores(prof)
    assert s == {"a": 11, "b": 12, "c": 7}
    assert borda(prof) == list("bac")
    # a beats b and c in a strict majority of the lists, yet b wins the Borda count.
    assert sum(r.index("a") < r.index("b") for r in prof) == 3
    assert sum(r.index("a") < r.index("c") for r in prof) == 3


def test_toy_runs():
    bm25 = [1, 2, 8, 7, 4]
    run = [1, 6, 8, 2, 4]
    s = borda_scores([bm25, run])
    assert s == {1: 12, 2: 8, 8: 8, 6: 6, 7: 4, 4: 4}
    assert borda([bm25, run]) == [1, 2, 8, 6, 4, 7]


def test_empty_and_single():
    assert borda([]) == []
    assert borda([[3, 1, 2]]) == [3, 1, 2]
    assert borda([[], [5]]) == [5]

History

Borda read a paper on elections to the French Academy of Sciences in 1770, and his memoir appeared in 1784 in the Academy's volume for 1781. He argued that plurality voting can elect a candidate whom most voters rank last, and proposed giving each candidate points by its place on each ballot. Condorcet, who edited the volume, criticized the rule because it can reject the candidate who wins every head-to-head majority, which is the failure shown in the example. In information retrieval, Aslam and Montague adapted it as Borda-fuse in 2001, and reported that it often beat the best single input system on TREC data; that is a measurement on those runs. Dwork, Kumar, Naor and Sivakumar used it the same year as a baseline for web metasearch, and Coppersmith, Fleischer and Rudra later proved its factor 5 bound for the Kemeny objective.

References

  1. Jean-Charles de Borda, Mémoire sur les élections au scrutin, Histoire de l'Académie Royale des Sciences, année 1781 (printed 1784), 657-665, the rule that gives a candidate points by its place on each ballot and elects the candidate with the largest total
  2. Javed A. Aslam and Mark H. Montague, Models for metasearch, Proceedings of the 24th Annual International ACM SIGIR Conference (SIGIR 2001), 276-284, Borda-fuse, the Borda count used to merge the result lists of several retrieval systems
  3. Don Coppersmith, Lisa K. Fleischer and Atri Rudra, Ordering by weighted number of wins gives a good ranking for weighted tournaments, ACM Transactions on Algorithms 6(3), Article 55 (2010), the proof that ordering by weighted number of wins, which for full rankings is the Borda order, is a 5-approximation of the minimum feedback arc set in a weighted tournament, and so of the Kemeny ranking
  4. Cynthia Dwork, Ravi Kumar, Moni Naor and D. Sivakumar, Rank aggregation methods for the Web, Proceedings of the 10th International World Wide Web Conference (WWW10), 613-622, Borda aggregation as one of the methods compared for metasearch, with partial lists

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example