in reply to Re: In-place sort with order assignment
in thread In-place sort with order assignment

I tried that, and I think it might work, but it takes an extraordinary amount of time. So much so that I never actually saw it complete. To counter that, I tried extracting and deleting the keys in batches of 1000:

my @ordered; while( my $n = keys %hash ) { my @temp; for ( 1 .. $n < 1000 ? $n : 1000 ) { push @temp, scalar each %hash; } delete @hash{ @temp }; push @ordered, @temp; }

But it still takes an extraordinary amount of time.

Update: The above has a precedence problem with the ternary expression! And results in for loop operating from 1 to 1.

Add a set of parens and things go much more quickly:

my @ordered; while( my $n = keys %hash ) { my @temp; for ( 1 .. ( $n < 1000 ? $n : 1000 ) ) { push @temp, scalar each %hash; } delete @hash{ @temp }; push @ordered, @temp; }

BTW: If I ever manage to get the keys out of the hash and into an array without blowing memory, then I intend to use your Sort::Key to sort them in-place. But, there doesn't seem to be a an in-place version of keysort that doesn't take a callback?

I can use keysort_inplace{ $_ } @ordered;, but doesn't the callback slow things down?

I can use rsort_inplace @array and just assign the numbers reversed, but it seems there should be a sort_inplace() version?


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP an inspiration; A true Folk's Guy

Replies are listed 'Best First'.
Re^3: In-place sort with order assignment
by salva (Canon) on Sep 19, 2010 at 16:41 UTC
    BTW: If I ever manage to get the keys out of the hash and into an array without blowing memory, then I intend to use your Sort::Key to sort them in-place. But, there doesn't seem to be a an in-place version of keysort that doesn't take a callback?

    It seems the interface is not very consistent... actually, the function exists, it is Sort::Key::_sort_inplace.

    In any case, perl builtin sort will perform equally faster as @k = sort @k gets optimized by the interpreter into an inplace operation.

    BTW, using the quicksort algorithm instead of the default merge sort will also help to reduce memory usage.

      @k = sort @k gets optimized by the interpreter into an inplace operation.

      When did that make it into the release? Cos everytime it comes up here, I try it out and it doesn't seem to work. (And my attempt to search for the release info fail.)

      For now, Sort::Key::_sort_inplace() will do me fine.

        That optimization was introduced here in 2004. Probably, the first stable release to incorporate it was perl 5.10.

        update: the optimization is documented in perl5100delta.