Top sort with cyclic test