PGsort

From WeBWorK_wiki
Revision as of 01:37, 5 January 2014 by Checkman (talk | contribs)
Jump to navigation Jump to search

PGSort

Description

General sorting macro

Syntax

PGsort( &sort_subroutine, @list);

Params

&sort_subroutine is a subroutine of two variables which defines order. Its output must be 0 or 1, with a 1 indicating the first argument is less than the second.

@list is the list to be sorted.

Returns

Returns list of elements in @list, ignoring duplicates. The order is unspecified.

Examples

join(" ",PGsort( sub {$_[0] &lt $_[1]} , (23,2,10,11,11,31) ); returns "2 10 11 11 23 31"

PGsort (sub { ($_[0] % 2) < ($_[1] % 2) }, @L ); will move the even numbers to the left of the odd numbers.

PGsort(

      sub { my ($P1, $P2) = @_; my $P1x = $P1 ->{data}[0], $P2x = $P2 -> {data}[0]; if ($P1x < $P2x) { return 1; }
      if ($P1x > $P2x) { return 0; } $P1 ->{data}[1] < $P2 -> {data}[1]; }
, ( Point (2,2), Point (1,3), Point(2,1) ) )
      returns (Point (1,3), Point (2,1), Point (2,2)) (now in lexigraphical order)

Notes

Using the perl sort directly in problems is not allowed for two reasons. The first is that the hardwired $a and $b variables used by sort can interfere with other values assigned to $a and $b. The second is that it is pretty easy to create closed loops with sort that hang the program. Currently nothing is done to prevent this, but later we may wish to modify num_sort and lex_sort to catch this problem.