Topological sorting is used to resolve the deps order,
actually depth-first search algorithm.

@see  https://en.wikipedia.org/wiki/Topological_sorting
327193
function resolveDeps(ast, result) {
  const {
    from: selfPath,
    graph,
    resolve,
    rootPath,
    rootTree,
  } = result.opts;

  const cwd = dirname(selfPath);
  const rootDir = dirname(rootPath);
  const processor = result.processor;
  const self = graph[selfPath] = graph[selfPath] || {};

  self.mark = TEMPORARY_MARK;

  const moduleExports = {};
  const translations = {};

  ast.walkRules(moduleDeclaration, rule => {
    if (importDeclaration.exec(rule.selector)) {
      rule.walkDecls(decl => translations[decl.prop] = decl.value);

      const dependencyPath = RegExp.$1.replace(/['"]/g, '');
      const absDependencyPath = resolveModule(dependencyPath, {cwd, resolve});

      if (!absDependencyPath) throw new Error(
        'Can\'t resolve module path from `' +
        cwd + '` to `' + dependencyPath + '`'
      );

      if (
        graph[absDependencyPath] &&
        graph[absDependencyPath].mark === TEMPORARY_MARK
      ) throw new Error(
        'Circular dependency was found between `' +
        selfPath + '` and `' + absDependencyPath + '`. ' +
        'Circular dependencies lead to the unpredictable state and considered harmful.'
      );

      if (!(
        graph[absDependencyPath] &&
        graph[absDependencyPath].mark === PERMANENT_MARK
      )) {
        const css = readFileSync(absDependencyPath, 'utf8');
        const lazyResult = processor.process(css, Object.assign({}, result.opts, {from: absDependencyPath}));

        updateTranslations(translations, lazyResult.root.exports);
      } else {
        updateTranslations(translations, graph[absDependencyPath].exports);
      }

      return void rule.remove();
    }

    rule.walkDecls(decl => moduleExports[decl.prop] = decl.value);
    rule.remove();
  });

  replaceSymbols(ast, translations);

  for (const token in moduleExports)
    for (const genericId in translations)
      moduleExports[token] = moduleExports[token]
        .replace(genericId, translations[genericId]);

  self.mark = PERMANENT_MARK;
  self.exports = ast.exports = moduleExports;

  // resolve paths
  if (cwd !== rootDir) resolvePaths(ast, cwd, rootDir);

  const importNotes = comment({
    parent: rootTree,
    raws: {before: rootTree.nodes.length === 0 ? '' : '\n\n'},
    text: ` imported from ${normalizeUrl(relative(rootDir, selfPath))} `,
  });

  const childNodes = ast.nodes.map(i => {
    const node = i.clone({parent: rootTree});

    if (
      typeof node.raws.before === 'undefined' ||
      node.raws.before === ''
    ) node.raws.before = '\n\n';

    return node;
  });

  rootTree.nodes = rootTree.nodes.concat(importNotes, childNodes);
}
1050580
public static Sort sort(Sort... sort) {
        if (sort.length == 1) {
            return sort[0];
        } else {
            Sort s = new Sort(true);
            for (Sort x : sort) {
                ((ArrayNode) s.node).add(x.toJson());
            }
            return s;
        }
    }
643945
def sort_topologically(graph):
    
    levels_by_name = {}
    names_by_level = defaultdict(list)

    def add_level_to_name(name, level):
        levels_by_name[name] = level
        names_by_level[level].append(name)


    def walk_depth_first(name):
        stack = [name]
        while(stack):
            name = stack.pop()
            if name in levels_by_name:
                continue

            if name not in graph or not graph[name]:
                level = 0
                add_level_to_name(name, level)
                continue

            children = graph[name]

            children_not_calculated = [child for child in children if child not in levels_by_name]
            if children_not_calculated:
                stack.append(name)
                stack.extend(children_not_calculated)
                continue

            level = 1 + max(levels_by_name[lname] for lname in children)
            add_level_to_name(name, level)

    for name in graph:
        walk_depth_first(name)

    return list(itertools.takewhile(lambda x: x is not None,
                                    (names_by_level.get(i, None)
                                     for i in itertools.count())))
569812
private int compareToLastRow(int depth)
        {
            for (int i = 0 ; i <= depth ; i++)
            {
                int p = currentRow[i], l = lastRow[i], r = clusteringComponents[i].size();
                if ((p == l) | (r == 1))
                    continue;
                return p - l;
            }
            return 0;
        }
7529
def layer_sort(hmap):
   
   orderings = {}
   for o in hmap:
      okeys = [get_overlay_spec(o, k, v) for k, v in o.data.items()]
      if len(okeys) == 1 and not okeys[0] in orderings:
         orderings[okeys[0]] = []
      else:
         orderings.update({k: [] if k == v else [v] for k, v in zip(okeys[1:], okeys)})
   return [i for g in sort_topologically(orderings) for i in sorted(g)]
1259956
private static <T extends Comparable<? super T>> void sort(T[] a, int n) {
        int inc = 1;
        do {
            inc *= 3;
            inc++;
        } while (inc <= n);

        do {
            inc /= 3;
            for (int i = inc; i < n; i++) {
                T v = a[i];
                int j = i;
                while (a[j - inc].compareTo(v) < 0) {
                    a[j] = a[j - inc];
                    j -= inc;
                    if (j < inc) {
                        break;
                    }
                }
                a[j] = v;
            }
        } while (inc > 1);
    }
619931
def topological_order_dfs(graph):
    
    n = len(graph)
    order = []
    times_seen = [-1] * n
    for start in range(n):
        if times_seen[start] == -1:
            times_seen[start] = 0
            to_visit = [start]
            while to_visit:
                node = to_visit[-1]
                children = graph[node]
                if times_seen[node] == len(children):
                    to_visit.pop()
                    order.append(node)
                else:
                    child = children[times_seen[node]]
                    times_seen[node] += 1
                    if times_seen[child] == -1:
                        times_seen[child] = 0
                        to_visit.append(child)
    return order[::-1]
1210274
function compareForwardSlotSegs(seg1, seg2) {
	// put higher-pressure first
	return seg2.forwardPressure - seg1.forwardPressure ||
		// put segments that are closer to initial edge first (and favor ones with no coords yet)
		(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
		// do normal sorting...
		compareSlotSegs(seg1, seg2);
}
723690
function orderNodes(ast) {
  var comments  = Array.isArray(ast.comments) ? ast.comments.slice() : [];
  var comparitor = ('sortIndex' in ast) ? compareIndex : compareLocation;
  return comments
    .concat(depthFirst(ast, ast.parent))
    .sort(comparitor)
    .map(setSortIndex);
}
54916
private void sort()
    {
        DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph = new DefaultDirectedWeightedGraph<>(
                    DefaultEdge.class);

        for (RuleProvider provider : providers)
        {
            graph.addVertex(provider);
        }

        addProviderRelationships(graph);

        checkForCycles(graph);

        List<RuleProvider> result = new ArrayList<>(this.providers.size());
        TopologicalOrderIterator<RuleProvider, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph);
        while (iterator.hasNext())
        {
            RuleProvider provider = iterator.next();
            result.add(provider);
        }

        this.providers = Collections.unmodifiableList(result);

        int index = 0;
        for (RuleProvider provider : this.providers)
        {
            if (provider instanceof AbstractRuleProvider)
                ((AbstractRuleProvider) provider).setExecutionIndex(index++);
        }
    }
220663
public List<ManagementGroupVertex> getGroupVerticesInTopologicalOrder() {

		final List<ManagementGroupVertex> topologicalSort = new ArrayList<ManagementGroupVertex>();
		final Deque<ManagementGroupVertex> noIncomingEdges = new ArrayDeque<ManagementGroupVertex>();
		final Map<ManagementGroupVertex, Integer> indegrees = new HashMap<ManagementGroupVertex, Integer>();

		final Iterator<ManagementGroupVertex> it = new ManagementGroupVertexIterator(this, true, -1);
		while (it.hasNext()) {
			final ManagementGroupVertex groupVertex = it.next();
			indegrees.put(groupVertex, Integer.valueOf(groupVertex.getNumberOfBackwardEdges()));
			if (groupVertex.getNumberOfBackwardEdges() == 0) {
				noIncomingEdges.add(groupVertex);
			}
		}

		while (!noIncomingEdges.isEmpty()) {

			final ManagementGroupVertex groupVertex = noIncomingEdges.removeFirst();
			topologicalSort.add(groupVertex);
			// Decrease indegree of connected vertices
			for (int i = 0; i < groupVertex.getNumberOfForwardEdges(); i++) {
				final ManagementGroupVertex targetVertex = groupVertex.getForwardEdge(i).getTarget();
				Integer indegree = indegrees.get(targetVertex);
				indegree = Integer.valueOf(indegree.intValue() - 1);
				indegrees.put(targetVertex, indegree);
				if (indegree.intValue() == 0) {
					noIncomingEdges.add(targetVertex);
				}

			}
		}

		return topologicalSort;
	}
1175347
def topological_sort(self):
        
        graph = self.graph

        in_degree = {}
        for u in graph:
            in_degree[u] = 0

        for u in graph:
            for v in graph[u]:
                in_degree[v] += 1

        queue = deque()
        for u in in_degree:
            if in_degree[u] == 0:
                queue.appendleft(u)

        sorted_graph = []
        while queue:
            u = queue.pop()
            sorted_graph.append(u)
            for v in sorted(graph[u]):
                in_degree[v] -= 1
                if in_degree[v] == 0:
                    queue.appendleft(v)

        if len(sorted_graph) == len(graph):
            return sorted_graph
        else:
            raise ValueError('graph is not acyclic')
544348
@Override
    public boolean isOrderDeterministic() {
        if ( ! super.isOrderDeterministic()) {
            return false;
        }
        IndexScanPlanNode index_scan = getInlineIndexScan();
        if ( ! index_scan.isOrderDeterministic()) {
            m_nondeterminismDetail = index_scan.m_nondeterminismDetail;
            return false;
        }
        return true;
    }
516429
function reduceByDepth(depthTree) {
    var order = 0
      , handled = {}
      , useInOrder = []
      ;

    // it's important to sort and reverse the key listing so that 
    // the most deeply depended on modules are always installed first and listed first in ender.js
    Object.keys(depthTree).sort().reverse().forEach(function (depth) {
      var depNames = depthTree[depth]
        ;

      depNames.forEach(function (depName) {
        if (!handled[depName]) {
          handled[depName] = true;
          useInOrder.push(depName);
        }
      });

    });

    return useInOrder;
  }
84086
def sort_targets(targets):
  

  roots, inverted_deps = invert_dependencies(targets)
  ordered = []
  visited = set()

  def topological_sort(target):
    if target not in visited:
      visited.add(target)
      if target in inverted_deps:
        for dep in inverted_deps[target]:
          topological_sort(dep)
      ordered.append(target)

  for root in roots:
    topological_sort(root)

  return ordered
1215889
protected static void sort(double[] d, double[] e) {
        int i = 0;
        int n = d.length;
        for (int j = 1; j < n; j++) {
            double real = d[j];
            double img = e[j];
            for (i = j - 1; i >= 0; i--) {
                if (d[i] >= d[j]) {
                    break;
                }
                d[i + 1] = d[i];
                e[i + 1] = e[i];
            }
            d[i + 1] = real;
            e[i + 1] = img;
        }
    }
135158
public List<T> sortTopologically(Set<T> payloads) {
    List<T> result = new ArrayList<>();

    Set<T> input = new HashSet<>(payloads);
    Deque<DirectedAcyclicGraphNode<T>> toVisit = new ArrayDeque<>(mRoots);
    while (!toVisit.isEmpty()) {
      DirectedAcyclicGraphNode<T> visit = toVisit.removeFirst();
      T payload = visit.getPayload();
      if (input.remove(payload)) {
        result.add(visit.getPayload());
      }
      toVisit.addAll(visit.getChildren());
    }

    Preconditions.checkState(input.isEmpty(), "Not all the given payloads are in the DAG: ",
        input);
    return result;
  }