def select(array, k): """Rearranges the array so that array[k] contains the kth smalles key; array[0] through array[k-1] are less than (or equal to) array[k]; and array[k+1] through array[n-1] are greather than (or equal to) array[k] :param array: the array :param k: the rank of the key :return: the key of rank k """ stdrandom.shuffle(array) lo = 0 hi = len(array) - 1 while hi > lo: i = _partition(array, lo, hi) if i > k: hi = i - 1 elif i < k: lo = i + 1 else: return array[i] return array[lo]
def main(args): from itu.algs4.stdlib import stdrandom as stdrandom # create random DAG with V vertices and E edges; then add F random edges V = int(args[0]) E = int(args[1]) F = int(args[2]) G = EdgeWeightedDigraph(V) vertices = [i for i in range(V)] stdrandom.shuffle(vertices) for _ in range(E): while True: v = stdrandom.uniformInt(0, V) w = stdrandom.uniformInt(0, V) if v >= w: break weight = stdrandom.uniformFloat(0.0, 1.0) G.add_edge(DirectedEdge(v, w, weight)) # add F extra edges for _ in range(F): v = stdrandom.uniformInt(0, V) w = stdrandom.uniformInt(0, V) weight = stdrandom.uniformFloat(0.0, 1.0) G.add_edge(DirectedEdge(v, w, weight)) print(G) # find a directed cycle finder = EdgeWeightedDirectedCycle(G) if finder.has_cycle(): print("Cycle: ") for e in finder.cycle(): print("{} ".format(e), end="") print() # or give topologial sort else: print("No directed cycle")
def sort(array): """Rearranges the array in ascending order, using the natural order.""" stdrandom.shuffle(array) _sort(array, 0, len(array) - 1)
def is_sorted(array): return _is_sorted(array, 0, len(array) - 1) def _is_sorted(array, lo, hi): for i in range(lo + 1, hi + 1): if array[i] < array[i - 1]: return False return True # print array to standard output def show(array): stdio.write(" ".join(array)) if __name__ == "__main__": array = stdio.readAllStrings() sort(array) assert is_sorted(array) show(array) # shuffle stdrandom.shuffle(array) # display results again using select print() for i in range(0, len(array)): ith = str(select(array, i)) stdio.writeln(ith)