There are 2 scales at play here -- Priority, and Speed.
Priority is evaluated first. While the majority of moves have a Priority of 0, specific moves range in Priority from +5 to -7. There are also a number of Abilities, battlefield effects, and Items that can change the Priority of moves, either in general or for specific Pokemon. Each turn, the game will separate all the moves selected by all the Pokemon participating into their respective brackets, and queueing the brackets up starting with +5, and working down 1 by 1 until it reaches -7.
Once queue has been set, each bracket is evaluated individually for the Pokemon whose moves are in that bracket, and compare their speed to decide the order in which the moves are actually used. Starting with the +5 bracket, the Pokemon with the highest Speed that is in that bracket will use their move first, then the next fastest second, and so on, until that bracket is empty. Then the same thing occurs in the +4 bracket, then the +3 bracket, etc, all the way down to the -7 bracket. In the event of a Speed tie (both Pokemon have the same value for Speed), the game will pick one of them at random, then alternate the order between them for as long as the matchup holds.
There is, however, a special case. The move Trick Room causes the Speed order to be evaluated backwards, starting with the slowest Pokemon instead of the fastest. But Priority is unaffected. The queue will still start with the +5 bracket, no matter what, but the Pokemon in that bracket will use their moves in the reverse order -- the slowest will move first, then the next slowest, etc. All the way down the Priority scale from +5 to -7.