Ah, a topological sort. Which you can be reduced to sorting if there are no conflicting requirements. (Sometimes you can do a topological sort faster than an ordinary sort, but you never need more time than a regular sort).

I'd preprocess the 'pred' arrays so I can faster search in them, after that, I'd do a regular sort:

#!/usr/bin/perl use strict; use warnings; my %hash = ( MEX1J => { desc => 'Job 2', pred => [qw /TEX1J/], }, MEX2J => { desc => 'Job End', pred => [qw /TEX1J MEX1J/], }, TEX1J => { desc => 'Job start', pred => [], }, ); # # Preprocess, transform the 'pred' arrays into hashes. # while (my ($key, $value) = each %hash) { $value->{pred_h} = {map {($_, 1)} @{$value->{pred}}}; } # # Sort keys. # my @keys = sort {$hash{$b}{pred_h}{$a} ? -1 : $hash{$a}{pred_h}{$b} ? 1 : 0} keys %hash; # # Print keys. # print "$_\n" for @keys; __END__ TEX1J MEX1J MEX2J
Note that you can write the sort block as:
{$hash{$a}{pred_h}{$b} - $hash{$b}{pred_h}{$a}}
but that's rather obscure, and you'd need to turn off warnings.
Perl --((8:>*

In reply to Re: Sort Algorithm (recursive?) by Perl Mouse
in thread Sort Algorithm (recursive?) by bertigo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.