问题描述
你好
我有以下代码:
#light
打开 系统跨度>
打开 System.Collections通用
let sortArray(array1 :int [])=
let 可变 排序= 0
letmutable sorted = 0
如果 (array1 = Array.sort(array1)) 然后
if (array1 = Array.sort(array1))then
排序<-1
如果 (Array.sort(array1)= Array.rev(array1)) 然后
if (Array.sort(array1) = Array.rev(array1))then
排序<--1
排序
let a1 = [ | 1; 2; 3 |]
let a2 = [ | 3; 2; 1 |]
let a3 = [ | 1; 2; 1 |]
let sortes1 = sortArray (a1)
let sortes2 = sortArray (a2)
let sortes3 = sortArray (a3)
结果sortArray(a1)为1; sortArray(a2)为-1; sortArray(a3)为0.
The result sortArray(a1) is 1; sortArray(a2) is -1; sortArray(a3) is 0.
我想知道数组是否较小,例如3或4个元素,上面的代码可以正常工作.
I want to know if the array is small size, like 3 or 4 elements, the above code works OK.
但是我会多次使用这样的代码,所以性能可能是一个问题,如果我使用简单的比较,代码可能看起来很难看.
But I will use such code for a lot of times, then performance could be an issue, if I use simple compare, the code could look ugly.
有没有人可以提供合适的"解决方案:对于小型数组(不超过5个元素),性能很好,但是代码看起来很整洁,并不难看.
Is there anyone who can offer a "suitable" solution: for small size array (no more than 5 elements), the performance is good, yet the code looks neat, not ugly.
谢谢
推荐答案
let sortArray (array1:int[]) =
let check f = array1 |> Seq.windowed 2 |> Seq.forall (fun i -> f i.[0] i.[1])
match check (<), check (>) with
| true, _ -> 1 //asc
| _, true -> -1 //desc
| _ -> 0 //disorder
更少的时间和内存:
let sortArray1 (array1:int[]) =
let rec checkSort f i =
if i = array1.Length - 1 then true else
if f array1.[i] array1.[i+1] then
checkSort f (i+1)
else false
match checkSort (<) 0, checkSort (>) 0 with
| true, _ -> 1
| _, true -> -1
| _ -> 0
这篇关于F#想要一个更好的解决方案,用整洁的代码排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!