**插入排序
**在这里插入代码片
// scal 函数式编程实现插入排序
def insertSortByFunction[A <% Ordered[A]](list:List[A]):List[A]={
def insertSort(unSort:List[A], sort:List[A]):List[A]=unSort match{
case head::tail =>insertSort(tail,insert(head,sort))
case Nil => sort
}
def insert(a: A, sort: List[A]):List[A]=sort match{
case head :: tail if(a>head) => head :: insert(a,tail)
case _ => a::sort
}
insertSort(list,Nil)
}
//java 思想编程
def insertSort(arr:Array[Int]): Unit ={
for(i <- 1 to arr.length -1){ //[1,arr.length-1]
breakable{
for(j <- 1 to i reverse){ //[1,i] until[1,i)
if(arr(j)<arr(j-1)){
arr(j)=arr(j-1)^arr(j)
arr(j-1)=arr(j-1)^arr(j)
arr(j)=arr(j-1)^arr(j)
} else{
break
}
println(arr.mkString(" "))
}
}
}
}
快排
在这里插入代码片
```// 函数式编程
// 利用 partition 实现 快排
def quickSortByPartition(list:List[Int]): List[Int] ={
list match {
case Nil => Nil
case List() => List()
case head :: tail =>
val (left, right) = tail.partition(_ < head) // tail.partition( x => )
quickSortByPartition(left) ::: head :: quickSortByPartition(right)
}
}
// 利用 filter 实现 快排
def quickSortByFilter(a:List[Int]):List[Int]={
if (a.length < 2) a
else quickSortByFilter(a.filter(_ < a.head)) ++
a.filter(_ == a.head) ++
quickSortByFilter(a.filter(_ > a.head))
}
// java 思想编程
def quickSort(arr:Array[Int],left:Int,right:Int): Unit ={
if(left<right){
val index = getIndex(arr:Array[Int],left:Int,right:Int)
quickSort(arr,left,index-1)
quickSort(arr,index+1,right)
}
}
def getIndex(arr:Array[Int],x:Int,y:Int):Int = {
var left = x
var right= y
val key = arr(left)
while(left<right){
while(arr(right)>key&&left<right){
right-=1
}
arr(left)=arr(right)
while(arr(left)<key&&left<right){
left+=1
}
arr(right)=arr(left)
}
arr(left)=key
left
}