在尝试了解有关排序算法和F#的更多信息时,我在F#中编写了一个插入排序。我是F#和函数式编程的完整菜鸟。
let insert (a: array<int>) i item =
i = i - 1
while i >= 0 && item < a.[i] do
a.[i + 1] = a.[i]
i = i - 1
a.[i + 1] = item
a
let sort (a: array<int>) =
for i in 1 .. (a.Length - 1) do
a = insert a i a.[i]
a
let a = [|3; 4; 1; 3;|]
a = sort a
for i in a do
printfn "%d" i
代码编译正常,但是当我运行可执行文件时......
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the boun
ds of the array.
at Isort.insert(Int32[] a, Int32 i, Int32 item)
at Isort.sort(Int32[] a)
at <StartupCode$isort>.$Isort.main@()
这个例外有点无益,因为它没有说超出范围的例外是...... 有没有办法在我的代码中修复此错误?
答案 0 :(得分:4)
几条评论:
mutable
。=
是相等的,而<-
是赋予可变值。改进版本:
let insert (a: int []) j item =
let mutable i = j - 1
while i >= 0 && item < a.[i] do
a.[i + 1] <- a.[i]
i <- i - 1
a.[i + 1] <- item
let sort (b: int []) =
let a = Array.copy b
for i in 1 .. (a.Length - 1) do
insert a i a.[i]
a
let a = [|3; 4; 1; 3; 5; 6; 5|]
let a' = sort a
for i in a' do printfn "%d" i
为了清楚起见,我修改了一些变量的名称。此外,辅助函数insert
可以返回unit
,而sort
最好返回一个新副本,而不是改变输入数组。