in reply to Re^6: In-place sort with order assignment
in thread In-place sort with order assignment
Update:
As you can see, this works but could be greatly improved with a data structure other than an array to maintain order. I converted the 2nd array to a hash to avoid doing a binary search since American football is about to come on and Sunday is family day :-)#!/usr/bin/perl use strict; use warnings; my %hash = map {$_ => undef} 'a' .. 'z'; my ($at_once, $cnt, @bot_n, %known) = (3, 0, (), ()); while (1) { while (my ($key, $val) = each %hash) { next if defined $val; if (exists $known{$key}) { $hash{$key} = $known{$key}; next; } my $inserted; for (0 .. $#bot_n) { if ($key lt $bot_n[$_]) { splice @bot_n, $_, 0, $key; $inserted = 1; last; } } push @bot_n, $key if ! $inserted; pop @bot_n if @bot_n > $at_once; } last if ! @bot_n; %known = (); for (@bot_n) { $known{$_} = ++$cnt; } @bot_n = (); } use Data::Dumper; print Dumper(\%hash);
Update 2: This requires N / M passes through the hash where N represents the total number of keys and M represents the maximum number of items to sort at once. Using an array and a hash to keep track of the current unknown bottom N is extremely inefficient (from runtime perspective) but data structures that support a faster run time also consume more memory. Finding a balance of speed and memory is left as an exercise for the reader :-)
Cheers - L~R
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^8: In-place sort with order assignment
by BrowserUk (Patriarch) on Sep 19, 2010 at 19:19 UTC | |
by Limbic~Region (Chancellor) on Sep 20, 2010 at 01:16 UTC | |
by BrowserUk (Patriarch) on Sep 20, 2010 at 07:40 UTC | |
by Limbic~Region (Chancellor) on Sep 20, 2010 at 13:18 UTC | |
by BrowserUk (Patriarch) on Sep 20, 2010 at 13:39 UTC | |
by Limbic~Region (Chancellor) on Sep 19, 2010 at 23:17 UTC | |
by Limbic~Region (Chancellor) on Sep 23, 2010 at 18:48 UTC |