in reply to Need help making my Merge Sort implementation stable

Why don't you just use the built in sort function with a custom comparison function? It's really fast, and I think it's also stable.
  • Comment on Re: Need help making my Merge Sort implementation stable

Replies are listed 'Best First'.
Re^2: Need help making my Merge Sort implementation stable
by taffer (Novice) on Jul 03, 2008 at 20:08 UTC
    My understanding is that it would sort just the field, not the entire row. For example, it would just swap @data$i$index, not the @data$i. If it does, I am not sure how to construct the custom comparison function. Could you point me towards some info that would get me started on learning how to construct a custom comparison function that would move an entire row of a multi-dimensional array instead of just the field?
      use Data::Dump 'pp'; # only used for output my @data = map { [ map { int rand(3) } 1 .. 5 ] } 1 .. 10; my @sorted = sort { $a->[1] <=> $b->[1] # sort by column 1 ascending || $a->[0] <=> $b->[0] # then column 0 || $b->[3] <=> $a->[3] # then column 3 descending } @data; pp @sorted;

      gives

      ( [0, 0, 2, 2, 2], [0, 0, 0, 0, 1], [0, 0, 2, 0, 1], [1, 0, 2, 2, 0], [2, 0, 0, 2, 2], [0, 1, 0, 1, 2], [1, 1, 0, 2, 2], [1, 1, 1, 1, 2], [0, 2, 2, 0, 0], [2, 2, 2, 0, 0], )


      Unless I state otherwise, all my code runs with strict and warnings
        Thank you, that did what I was needing to. Now I need to try to understand exactly what the BLOCK is telling it to do. I am just learning about array referencing and dereferencing s oI get a bit mixed up, still. I'll have to look at this some more to really grasp what is going on.
      My understanding is that it would sort just the field, not the entire row.

      Not quite. Look at this small example:

      use strict; use warnings; use Data::Dumper; my @items = ( [0, 4, 2], [2, 5, 8], [-5, 0, -3], [3, 4, 0], [1, 4, 8], ); my @sorted = sort { $a->[1] <=> $b->[1] } @items; print Dumper \@sorted; __END__ $VAR1 = [ [ -5, 0, -3 ], [ 0, 4, 2 ], [ 3, 4, 0 ], [ 1, 4, 8 ], [ 2, 5, 8 ] ];

      (I tidied up the output a bit to include less line breaks).

      You can see that the array is sorted by the second column, but the result is a list of array references, just like the input.

      sort is very powerful, you only have to know how to use it ;-)