注意,mxs的下标是从1开始,1to10,就表示1to10,而不是1to9
二分查找
--列表必须有序
fn bin_stream arr target =
(
left = 1
right = arr.count
while left < right - 1 do --可被查找,候选区有值
(
mid = (left + right) / 2
if arr[mid] == target then
return mid
else if arr[mid] > target then --待查找的值在mid左边
right = mid
else
left = mid
/* print left
print right
if keyboard.escPressed do exit */
)
return undefined
)
arr = for i = 1 to 500000 collect i
bin_stream arr 755
low b 三法
冒泡排序
--列表每2个相邻的数,如果前面比后面大,则交换2个数顺序
fn bubble_sort arr =
(
for i = 1 to arr.count do --遍历的次数
(
for j = 1 to (arr.count - i) do --指针移动的位置
(
--如果前面比后面大,则交换2个数顺序
--降序直接用 <
if arr[j] > arr[j+1] then
swap arr[j] arr[j+1]
)
)
)
arr = for i = 1 to 15 collect (random 1 500)
bubble_sort arr
--优化,提前排好直接退出循环
for i = 1 to arr.count do
(
changed = false
for j = 1 to (arr.count - i) do
(
if arr[j] > arr[j+1] then
(
swap arr[j] arr[j+1]
changed = true
)
)
--如果未更改则退出
if not changed exit
)
选择排序
--每次把最小的数放到数组最前方
fn select_sort arr =
(
for i = 1 to arr.count do
(
minIndx = i
--从被占位的地方开始
for j = i to arr.count do
(
--找到最小的数
if arr[j] < arr[minIndx] do
minIndx = j
)
--最小的数,交换到前方
swap arr[i] arr[minIndx]
)
)
arr = #(1,3,9,2,4)
select_sort arr
arr
插入排序
fn insert_sort arr =
(
-- i 表示摸到的牌,从第二张开始摸
for i = 2 to arr.count do
(
tmp = arr[i] --摸到的牌的内容
j = i - 1 --手里的牌总数
--j > 0 防止 下标取0
while j > 0 and arr[j] > tmp do
(
arr[j+1] = arr[j]
j -= 1
if keyboard.escPressed do exit
)
arr[j + 1] = tmp
print ("-->" + arr as string)
)
)
arr = #(100,7,9,2,4,6)
insert_sort arr
NB三法
快速排序