# Difference between revisions of "PGsort"

(from ur manpages) |
(Clarified, more examples given by C C Heckman (January 2014)) |
||

Line 11: | Line 11: | ||

'''Params''' |
'''Params''' |
||

− | <blockquote> &sort_subroutine is a subroutine of two variables which defines order. |
+ | <blockquote> &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. <br /><br />@list is the list to be sorted.</blockquote> |

'''Returns''' |
'''Returns''' |
||

Line 19: | Line 19: | ||

'''Examples''' |
'''Examples''' |
||

− | <blockquote> join(" ",PGsort( sub {$_[0] <=> $_[1]} , (23,2,10,11,11,31) |
+ | <blockquote> join(" ",PGsort( sub {$_[0] <=> $_[1]} , (23,2,10,11,11,31) ); returns "2 10 11 11 23 31"</blockquote> |

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

+ | <blockquote> PGsort( <br /> |
||

+ | sub { my ($P1, $P2) = @_; |
||

+ | my $P1x = $P1 ->{data}[0], $P2x = $P2 -> {data}[0]; |
||

+ | if ($P1x < $P2x) { return 1; }<br /> |
||

+ | |
||

+ | if ($P1x > $P2x) { return 0; } |
||

+ | $P1 ->{data}[1] < $P2 -> {data}[1]; } |
||

+ | <br />, |
||

+ | ( Point (2,2), Point (1,3), Point(2,1) ) ) <br /> returns (Point (1,3), Point (2,1), Point (2,2)) (now in lexigraphical order) |
||

+ | </blockquote> |
||

'''Notes''' |
'''Notes''' |

## Revision as of 23:59, 2 January 2014

### 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] <=> $_[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.