topological sort in matlab

main.m
function topologicalSort(graph)
    nodes = numel(graph);
    degrees = zeros(1, nodes);
    for node = 1:nodes
        degrees(node) = sum(graph(:, node));
    end

    sorted = [];
    for i = 1:nodes
        node = find(degrees == 0, 1);
        if isempty(node)
            error('Graph has a cycle');
        end
        sorted = [sorted, node];
        degrees(node) = -1;
        for j = 1:nodes
            if graph(node, j) == 1
                degrees(j) = degrees(j) - 1;
            end
        end
    end
    
    disp('Topological order:');
    disp(sorted);
end
578 chars
26 lines

This MATLAB function topologicalSort takes an adjacency matrix graph of a directed acyclic graph as input and computes the topological order of the nodes. It will display the nodes in a topological order, or throw an error if the input graph has a cycle.

gistlibby LogSnag