例如归并排序,清晰明了。
object
MergeSort
extends
App {
val
oldList
=
List[Int](
12
,
40
,
26
,
89
,
75
,
44
,
32
,
65
,
18
)
val
list
=
mergeSort(oldList)
println(list)
def
mergeSort(list
:
List[Int])
:
List[Int]
=
{
val
n
=
list.size/
2
if
(n
==
0
)list
else
{
val
(xs,ys)
=
list.splitAt(n);
merge(mergeSort(xs),mergeSort(ys))
}
}
def
merge(xs
:
List[Int],ys
:
List[Int])
:
List[Int]
=
{
(xs,ys)
match
{
case
(
_
,Nil)
=
>xs
case
(Nil,
_
)
=
>ys
case
(x
::
list
1
,y
::
list
2
)
=
> {
if
(x>y) y
::
merge(list
2
,xs)
else
x
::
merge(list
1
,ys)
}
}
}
快速排序
def quickSort(xs: Array[Int]): Array[Int] = {
if(xs.length <= 1) xs
else{
val pivot = xs(xs.length / 2)
Array.concat( //合并
quickSort(xs filter (pivot >)),
xs filter (pivot ==),
quickSort(xs filter (pivot <))
)
}
}