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.
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)