Osmosian普通英语唯一的复合数据类型是记录和双向链接列表。当我们需要对列表进行排序时,我们将使用下面将描述的简单的递归合并排序。但是首先,我们需要进行排序。让我们对水果进行排序,然后从类型定义开始:
A fruit is a thing with a name.
当“事物”一词出现在类型定义中时,我们的编译器会在幕后发挥一些魔力,使事物(双关语)更加强大和灵活。例如,以上定义实际上导致定义以下数据类型:
因此,水果实际上只不过是包含水果记录地址的指针。
每个16字节的水果记录都有一个隐藏的8字节前缀,带有两个指针,用于将这些记录与水果的名称(即字符串)链接到列表中。纯英语字符串存储在堆中,并且可以是任何长度。因此,水果记录中的名称实际上只是分别指向堆上字符串的第一个字节和最后一个字节的两个指针。字符串内存是自动管理的,但事物内存是由程序员管理的。
编译器生成的第三种类型用作“水果记录”列表的锚点。这样的列表被简单地(直观地)称为“水果”,即“水果”的复数。
现在,让我们以随机顺序将一些水果添加到列表中,并对它们进行排序。以下是我们测试程序中的顶级句子:
To run:
Start up.
Create some fruits.
Write the fruits on the console.
Skip a line on the console.
Sort the fruits.
Write the fruits on the console.
Destroy the fruits.
Wait for the escape key.
Shut down.
以下是将被用来“创建一些水果”的例程:
To create some fruits:
Add "banana" to the fruits.
Add "apple" to the fruits.
Add "orange" to the fruits.
Add "bacon" to the fruits.
Add "pineapple" to the fruits.
Add "pomegranate" to the fruits.
Add "tomato" to the fruits.
Add "grape" to the fruits.
Add "fig" to the fruits.
Add "date" to the fruits.
To add a name to some fruits:
Allocate memory for a fruit.
Put the name into the fruit's name.
Append the fruit to the fruits.
现在我们可以进行排序了。这是排序例程:
To sort some fruits:
If the fruits' first is the fruits' last, exit.
Split the fruits into some left fruits and some right fruits.
Sort the left fruits.
Sort the right fruits.
Loop.
Put the left fruits' first into a left fruit.
Put the right fruits' first into a right fruit.
If the left fruit is nil, append the right fruits to the fruits; exit.
If the right fruit is nil, append the left fruits to the fruits; exit.
If the left fruit's name is greater than the right fruit's name,
move the right fruit from the right fruits to the fruits; repeat.
Move the left fruit from the left fruits to the fruits.
Repeat.
当我们运行该程序时,控制台上的输出如下所示:
但是速度很快吗?让我们看看使用此修改后的测试程序:
To run:
Start up.
Write "Working..." on the console.
Put 10000 into a count.
Create some fruits using "apple" and the count.
Start a timer. Sort the fruits. Stop the timer.
Write the timer then " milliseconds for " then the count on the console.
Destroy the fruits.
Put 100000 into the count.
Create the fruits using "apple" and the count.
Start the timer. Sort the fruits. Stop the timer.
Write the timer then " milliseconds for " then the count on the console.
Destroy the fruits.
Put 1000000 into the count.
Create the fruits using "apple" and the count.
Start the timer. Sort the fruits. Stop the timer.
Write the timer then " milliseconds for " then the count on the console.
Destroy the fruits.
Wait for the escape key.
Shut down.
这次的结果从一开始就看起来像这样:
apple 0010000
apple 0009999
apple 0009998
...
控制台上的输出如下所示:
我承认这不是很线性。但也不是指数级的。十倍的记录需要大约十倍的时间来排序。有一种技术上的说法是使用大的“ O”,很少的“ n’s”和“ logs”之类的东西,但是普通的英语程序员通常不这么认为。就像普通英语程序员所期望的那样,它是稳定的-具有重复排序值的记录将保留其原始顺序。
好,简单,有用的东西。