notes

Personal notes
git clone git://git.laack.co/notes.git
Log | Files | Refs

FisherYatesShuffle.md (597B)


      1 # Fisher Yates Shuffle
      2 
      3 **Definition:** The Fisher-Yates sorting algorithm is the most common sorting algorithm whereby you iterate backwards through the list swapping the current index with an arbitrary index that is less than the current until reaching the 0th index.
      4 
      5 Implementation:
      6 
      7 ```python
      8 
      9 def swap(ls, pos1, pos2):
     10     temp = ls[pos1]
     11     ls[pos1] = ls[pos2]
     12     ls[pos2] = temp
     13     return ls
     14 
     15 def shuffle(ls):
     16     i = len(ls) - 1
     17     # 0 does not need to swap
     18     while i > 0:
     19         rnd = random.randint(0,i-1)
     20         swap(ls,pos1=rnd, pos2=i)
     21         i -= 1
     22     
     23     return ls
     24 
     25 ```