0
点赞
收藏
分享

微信扫一扫

scala数据结构和算法-09-基于插入排序的基数排序


基数排序是另外一种比较有特色的排序方式,它是怎么排序的呢?我们可以按照下面的一组数字做出说明:12、 104、 13、 7、 9

    (1)按个位数排序是12、13、104、7、9

    (2)再根据十位排序104、7、9、12、13

    (3)再根据百位排序7、9、12、13、104

 

package data

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

object RadixSort {
def insertSort(source:ListBuffer[Int],radixSource:ListBuffer[Int]):ListBuffer[Int]={
for(i<-1 until radixSource.length){
for(j<-(1 to i).reverse){
val current=radixSource(j);
val prev=radixSource(j-1);
if(current<prev){
radixSource(j-1)=current;
radixSource(j)=prev;
val tmp=source(j-1)
source(j-1)=source(j);
source(j)=tmp;
}
}
}
source
}
def getMaxLength(source:ListBuffer[Int])={
var maxCount=0;
for(i<-0 until source.length){
var tmp=source(i)
var count=0
while(tmp/10>0){
count+=1
tmp=tmp/10
}
count+=1
if(count>maxCount){
maxCount=count;
}

}
maxCount
}
def radixSort(source:ListBuffer[Int])={
val maxCount=getMaxLength(source);
for(i<-1 to maxCount){
var radixSource=ListBuffer[Int]()
for(j<-0 until source.length){
var tmp=source(j)
var k=i;
while(k-1>0){
tmp=tmp/10
k-=1
}
radixSource.append(tmp%10)
}
insertSort(source,radixSource)
}
source
}
def main(args: Array[String]): Unit = {
val source=ListBuffer(33,12,21,90,101,8,10,67,40,109,121,5,11111)
println(getMaxLength(source));
println(radixSort(source).mkString(","))
}
}

 

 

 

 

 

举报

相关推荐

0 条评论