Only reason I see here is that you take a,b for comparision from tiles[] but you change the array tile_order.
Until you either compare with tile_order or change tiles[] it can't end with this structure as tiles is unchanged on each recheck but tile_order gets swapped all the time.
Until you either compare with tile_order or change tiles[] it can't end with this structure as tiles is unchanged on each recheck but tile_order gets swapped all the time.