Refactored shuffle function to improve efficiency