traverse the array until we reach at an element which is already marked or which could not be marked .
while ( arr [ val - 1 ] != val ) { nextval = arr [ val - 1 ] ; arr [ val - 1 ] = val ; val = nextval ; if ( val <= 0 val > n ) break ; } }