Skip to content

Commit 1b40050

Browse files
committed
new file: Sort/dream_sort.pl
1 parent 841e959 commit 1b40050

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1256,6 +1256,7 @@ A nice collection of day-to-day Perl scripts.
12561256
* [Chat server](./Socket/chat_server.pl)
12571257
* Sort
12581258
* [Binsertion sorting algorithm](./Sort/binsertion_sorting_algorithm.pl)
1259+
* [Dream sort](./Sort/dream_sort.pl)
12591260
* Subtitle
12601261
* [Srt-delay](./Subtitle/srt-delay)
12611262
* [Srt assembler](./Subtitle/srt_assembler.pl)

Sort/dream_sort.pl

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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

Comments
 (0)