scala数据结构和算法-04-快速排序实现
2017-01-03 13:19
483 查看
package data import scala.collection.mutable.ListBuffer import scala.collection.mutable.ListBuffer object QuickSort { def quickSort[T<% Ordered[T]](source:ListBuffer[T],left:Int,right:Int):ListBuffer[T]={ if(left==right)ListBuffer() else{ val index=partition(source,left,right) if(left==index){ if(right-index>=2){ quickSort(source,index+1,right) } }else if(right==index){ if(index-left>=2){ quickSort(source,left,index-1) } }else{ if(index-left>=2){ quickSort(source,left,index-1) } if(right-index>=2){ quickSort(source,index+1,right) } } source } } def partition[T<%Ordered[T]](source:ListBuffer[T],left:Int,right:Int):Int={ val cmp=source(left) var leftIndex=left var rightIndex=right var direction=true; while(leftIndex<rightIndex){ if(direction){ if(source(rightIndex)<cmp){ source(leftIndex)=source(rightIndex); leftIndex+=1; direction=(!direction); }else{ if(leftIndex<rightIndex){ rightIndex-=1; } } } if(!direction){ if(source(leftIndex)>=cmp){ source(rightIndex)=source(leftIndex) rightIndex-=1 direction=(!direction); }else{ if(leftIndex<rightIndex){ leftIndex+=1; } } } } source(leftIndex)=cmp; leftIndex } def main(args: Array[String]): Unit = { val source=ListBuffer(1,3,7,5,4,15,3,9,6,8,33,12,14,12,17,16,18); println(quickSort(source,0,source.length-1).mkString(",")) } }
相关文章推荐
- 数据结构和算法学习系列之快速排序的Partition函数一种实现方法
- scala数据结构和算法-05-插入排序实现
- 【算法与数据结构】冒泡、插入、归并、堆排序、快速排序的Java实现代码
- scala数据结构和算法-02-用模式匹配实现合并排序
- [置顶] 【scala 数据结构和算法】Scala实现:冒泡排序
- 一步步学习数据结构和算法之快速排序效率分析及java实现
- scala数据结构和算法-03-冒泡排序实现
- [置顶] 【scala 数据结构和算法】Scala实现:归并排序
- T-SQL实现数据结构中的冒泡算法和快速排序
- [置顶] 【scala 数据结构和算法】Scala实现:快速排序
- 【算法和数据结构】排序(四)归并排序和快速排序(C++实现)
- scala数据结构和算法-01-用scala实现合并排序
- 【数据结构&&算法系列】快速排序简单介绍及实现
- 一步步学习数据结构和算法之快速排序效率分析及java实现
- 常用数据结构2——栈,实现PUSH、POP和取最小值操作算法时间复杂度为o(1)
- C#数据结构和算法学习系列七----队列、队列的实现和应用
- 数据结构各种算法实现(C++模板)
- 数据结构各种算法实现C++
- 算法与数据结构课程中的c++实现的顺序表和链表
- 数据结构经典算法汇总___图的邻接矩阵实现