Created
December 7, 2018 18:48
-
-
Save ajs/b9d77f8e8f0a7032403aba7832a64983 to your computer and use it in GitHub Desktop.
Perl 6 quicksort demo expanded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
# Empty list sorts to the empty list | |
multi quicksort([]) { () } | |
# Called on a scalar item (not a list of one item) return it as a list | |
multi quicksort($item) { $item, } | |
# Otherwise, extract first item as pivot... | |
multi quicksort([$pivot, *@rest]) { | |
return $pivot, unless @rest.elems; | |
# Partition | |
my $before := @rest.grep: {$^item before $pivot}; | |
my $after := @rest.grep: {$^item !before $pivot}; | |
# Sort the partitions. | |
flat quicksort($before), $pivot, quicksort($after) | |
} | |
put quicksort 7; # sort a single item | |
put quicksort <hill fall year tire over hose week>; # sort words | |
put quicksort flat ^10, ^10; # sort 0-9, 0-9 | |
put quicksort quicksort ^10; # sort result of sort 0-9 | |
put quicksort (^1000).pick(10); # sort 10 random values in range 0-999 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment