Gale-Shapley Algorithm

Pseudo code for the Gale-Shapley Algorithm

GSA(M, W){

    // Initialization
    Mark all m ∈ M and w ∈ W as free

    while( ∃ free man m who hasn't proposed to all women )
         w ← highest woman on m's list that has not been proposed to

        // m proposes to w
         if(w is free)
             m and w get engaged
         elsif( w is engaged to m' but prefers m to m' )
             w breaks engagement to m'
             m' becomes free again
             m and w become engaged
         else
             m stays free
         endif
    end while

    return set of engaged pairs
}