Skip to content

Instantly share code, notes, and snippets.

@na-ka-na
Created December 28, 2013 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save na-ka-na/8165704 to your computer and use it in GitHub Desktop.
Save na-ka-na/8165704 to your computer and use it in GitHub Desktop.
use strict;
use warnings 'all';
use Tie::File;
use Fcntl 'O_RDWR';
my $file = "to-sort.txt";
tie my @nums, 'Tie::File', $file
, mode => O_RDWR
, recsep => ', '
, memory => 20_000_000 # max 20 MB read buffer
, autodefer => 0 # flush every write
;
mysort();
sub mysort {
return if (scalar @nums <= 1);
chomp $nums[-1];
TOP: for (my $i=1; $i < scalar @nums; $i++) {
if (mycmp($nums[$i-1], $nums[$i]) > 0) {
my ($num) = splice @nums, $i, 1; # remove the number
# find correct position
for (my $j=0; $j < $i; $j++) {
if (mycmp($num, $nums[$j]) <= 0) {
# found it, put the number here
splice @nums, $j, 0, $num;
next TOP;
}
}
}
}
}
sub mycmp {
#return rand() - 1/2;
return $_[0] <=> $_[1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment