External sort: Difference between revisions

Added Perl example
(Added Go)
(Added Perl example)
Line 273:
</pre>
 
=={{header|pythonPerl}}==
Simulate task by reading from 'DATA' handle and using tiny record limit. As written, works for any numeric input, but could define any kind of customized sorting.
<lang perl>use strict;
use warnings;
 
my $max = 4; # records per merge file
my(@chunk,@tempf);
 
sub mysort ($$) { return $_[0] <=> $_[1] }
 
sub store {
my($a) = @_;
my $f = IO::File->new_tmpfile; # self-deleting after program exit
print $f sort mysort @$a;
seek $f, 0, 0 or warn "Oops: $!";
push(@tempf, { fh => $f, queued => scalar <$f> } );
}
 
# read input and create sorted temporary files
while (<DATA>) {
push @chunk, $_;
store(\@chunk), @chunk = () if @chunk == $max;
}
store(\@chunk) if @chunk;
 
# merge everything
while (1) {
my($lowest) = (sort { mysort($a->{queued}, $b->{queued}); } grep(defined $_->{queued}, @tempf) )[0];
last unless $lowest->{queued};
print $lowest->{queued};
$lowest->{queued} = $lowest->{fh}->getline();
}
 
__DATA__
432
345
321
543
987
456
678
123
765
567
876
654
789
234</lang>
{{out}}
<pre>123
234
321
345
432
456
543
567
654
678
765
789
876
987</pre>
 
=={{header|Python}}==
A technique demonstrated with a short string character data.
<lang python>
2,392

edits