Jump to content

User:Ilmari Karonen/sandbox

From Wikipedia, the free encyclopedia

This is the current revision of this page, as edited by Ilmari Karonen (talk | contribs) at 13:09, 29 June 2010 (pseudocode). The present address (URL) is a permanent link to this version.

(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

A Fisher-Yates shuffle with zero-based arrays:

    i ← length( a ) − 1
    while i ≥ 1
        j ← rand( 0, i )
        ( ai, aj ) ← ( aj, ai )
        ii − 1
    repeat

Alternative notation:

    for i := length( a ) − 1 down to 1 step -1 do
        j := rand( 0, i );
        swap( ai, aj ) od;

Note: rand( a, b ) is assumed to return a uniformly distributed random integer from a to b inclusive.