magnitopic
Back to projects
  • C
  • Algorithms
  • Sorting
  • Data Structures
  • 42

Push Swap

Sort a stack of integers using only two stacks and eleven operations (push, rotate, reverse-rotate, swap) in as few moves as possible. Small inputs (≤5) use a hardcoded optimal sort; larger inputs use a greedy algorithm that calculates the cost to insert every element and always picks the cheapest move, with a synergy optimisation that merges simultaneous same-direction rotations on both stacks into a single combined instruction. Typically achieves ~750 moves for 100 numbers and ~6 500 for 500.