sorting tournament seeds

前端 未结 6 1239
夕颜
夕颜 2021-02-09 17:40

I\'m making a HTML/JS powered single/double elimination bracket web app. I am struggling to figure out how to assign the first round matches from a list of seeded teams/players.

6条回答
  •  花落未央
    2021-02-09 18:11

    This is probably not as efficient as @alex's answer using a custom sort function, but certainly easier to write and understand:

    // This algorithm assumes that seeds.length is an even number
    var seeds = [1, 2, 3, 4, 5, 6, 7, 8],
        firstRound = [];
    
    while (seeds.length)
    {
        firstRound.push(seeds.shift());
        firstRound.push(seeds.pop());
    }
    
    // seeds is now empty
    // firstRound is now [1, 8, 2, 7, 3, 6, 4, 5]
    

    Demo 1


    Actually, I just thought of a faster algorithm (in-place "sorting", takes O(n) time):

    // Also assumes that seeds.length is an even number
    var seeds = [1, 2, 3, 4, 5, 6, 7, 8],
        numSeeds = seeds.length,
        stop = numSeeds >> 1,
        temp;
    
    for (var i=1; i

    Demo 2

    Note that neither of these algorithms generates exactly the same order of pairs as in the OP, but they both generate the same set of pairs:

    • (1,8)
    • (2,7)
    • (3,6)
    • (4,5)

提交回复
热议问题