def bubbleSort(array: Array[Int]):Unit={var swap =true//设置swap值,如果没有发生交换则证明已经有序,不必再继续循环var temp =0for(i <-0 until array.length if swap ==true){
swap =falsefor(j<-0 until array.length-i-1){//注意这里的判断条件if(array(j)>array(j+1)){
temp = array(j)
array(j)= array(j+1)
array(j+1)= temp
swap =true}}}}
插入排序
def insertSort(array: Array[Int]):Unit={var temp =0;var index =0for(i<-1 until array.length){if(array(i)<array(i-1)){
temp = array(i);for(j<-(0 to i-1) reverse;if array(j)>temp){
array(j+1)= array(j)
index = j
}
array(index)= temp//注意插入位置}}}
选择排序
def selectSort(array: Array[Int]):Unit={var k:Int=0var min:Int=0for(i <-0 until array.length){
min = array(i)
k = i
for(j <- i until array.length){if(min > array(j)){
min = array(j)
k = j //注意k值和min都要随着变化}}if(k != i){
array(k)= array(i)
array(i)= min
}}}
快速排序
def quickSort(array: Array[Int],start:Int,end:Int):Unit={if(end - start <=0)return//注意递归退出条件val pivot = array(start)var i = start
var j = end
while(i<j){while(i<j && array(j)>=pivot) j -=1
array(i)= array(j)//注意这里直接覆盖即可,无需交换while(i<j && array(i)<=pivot) i +=1
array(j)= array(i)}
array(i)= pivot
quickSort(array,start,i-1)
quickSort(array,i+1,end)}
归并排序
def mergeSort(array: Array[Int],low:Int,high:Int):Unit={if(low < high){//注意这里应该使用if判断而不是whileval mid = low +(high - low)/2
mergeSort(array,low,mid)
mergeSort(array,mid+1,high)
merge(array,low,mid,high)}}def merge(array: Array[Int],low:Int,mid:Int,high:Int):Unit={var i = low
var j = mid +1val temp =new Array[Int](high-low+1)//使用了一个临时数组,也可以定义为全局的,减少每次申请内存的消耗var k =0while(i<=mid&&j<=high){if(array(i)<=array(j)){
temp(k)= array(i)
i +=1
k +=1}else{
temp(k)= array(j)
j +=1
k +=1}}while(i <= mid){temp(k)= array(i);i +=1;k +=1}while(j <= high){temp(k)= array(j);j +=1;k +=1}
i = low
for(index <-0 until k){
array(i)= temp(index)
i +=1}}
冒泡排序def bubbleSort(array: Array[Int]):Unit={ var swap = true//设置swap值,如果没有发生交换则证明已经有序,不必再继续循环 var temp = 0 for(i <- 0 until array.length if swap == true){ swap = false for(j<- 0 until array.length-i-1){//注意这里的判断条件 i.