The Gale-Shapley Algorithm is meant to solve the stable matching problem with O(n2). In the matching problem, there are n women and n men. Each person has a preference list ranking every member of the opposite sex for marriage. The goal is to create couples such that no one would be better off leaving their marriage for someone else.
The following is pseudocode from Wikipedia:
algorithm stable_matching is
Initialize all m ∈ M and w ∈ W to free
while ∃ free man m who still has a woman w to propose to do
w := first woman on m's list to whom m has not yet proposed
if w is free then
(m, w) become engaged
else some pair (m', w) already exists
if w prefers m to m' then
m' becomes free
(m, w) become engaged
else
(m', w) remain engaged
end if
end if
repeat
Every man (n) can propose up to n times in the worst case. That gives the while loop O(n^2). But there's a line in the inner loop which concerns me:
if w prefers m to m' then
Shouldn't this mean we have to iterate through a preference list to find who appears first? Wouldn't that also be O(n), making the algorithm O(n3)?
My preference lists for men and women are both of type int[n][n]. The outer index is the id of the person who owns the inner list. The inner list contains the ids of everyone in the opposite sex, ordered by the owner's preference.