|
| 1 | +#!/usr/bin/perl |
| 2 | + |
| 3 | +# Author: Daniel "Trizen" Șuteu |
| 4 | +# Date: 19 August 2025 |
| 5 | +# https://github.com/trizen |
| 6 | + |
| 7 | +# A recursive sorting algorithm for strings, based on a dream that I had, similar to Radix sort. |
| 8 | + |
| 9 | +# The running time of the algorithm is: |
| 10 | +# O(n * len(s)) |
| 11 | +# where `n` is the number of strings being sorted and `s` is the longest string in the array. |
| 12 | + |
| 13 | +use 5.036; |
| 14 | +use List::Util qw(shuffle); |
| 15 | +use Test::More tests => 20; |
| 16 | + |
| 17 | +sub dream_sort($arr, $i = 0) { |
| 18 | + |
| 19 | + my @buckets; |
| 20 | + |
| 21 | + foreach my $item (@$arr) { |
| 22 | + my $byte = substr($item, $i, 1) // ''; |
| 23 | + if ($byte eq '') { |
| 24 | + $byte = 0; |
| 25 | + } |
| 26 | + else { |
| 27 | + $byte = ord($byte) + 1; |
| 28 | + } |
| 29 | + push @{$buckets[$byte]}, $item; |
| 30 | + } |
| 31 | + |
| 32 | + my @sorted; |
| 33 | + |
| 34 | + if (defined($buckets[0])) { |
| 35 | + push @sorted, @{$buckets[0]}; |
| 36 | + } |
| 37 | + |
| 38 | + foreach my $k (1 .. $#buckets) { |
| 39 | + my $entry = $buckets[$k]; |
| 40 | + if (defined($entry)) { |
| 41 | + if (scalar(@$entry) == 1) { |
| 42 | + push @sorted, $entry->[0]; |
| 43 | + } |
| 44 | + else { |
| 45 | + push @sorted, @{__SUB__->($entry, $i + 1)}; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return \@sorted; |
| 51 | +} |
| 52 | + |
| 53 | +sub sort_test($arr) { |
| 54 | + my @sorted = sort @$arr; |
| 55 | + is_deeply(dream_sort($arr), \@sorted); |
| 56 | + is_deeply(dream_sort([reverse @$arr]), \@sorted); |
| 57 | + is_deeply(dream_sort(\@sorted), \@sorted); |
| 58 | + is_deeply(dream_sort([shuffle(@$arr)]), \@sorted); |
| 59 | +} |
| 60 | + |
| 61 | +sort_test(["abc", "abd"]); |
| 62 | +sort_test(["abc", "abc"]); |
| 63 | +sort_test(["abcd", "abc"]); |
| 64 | +sort_test(["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]); |
| 65 | + |
| 66 | +sort_test( |
| 67 | + do { |
| 68 | + open my $fh, '<:raw', __FILE__; |
| 69 | + local $/; |
| 70 | + [split(' ', scalar <$fh>)]; |
| 71 | + } |
| 72 | +); |
0 commit comments