您的位置:首页 > 职场人生

程序员必知的8大排序(四)-------归并排序,基数排序(java实现)

2012-05-31 17:07 225 查看
7、归并排序

(1)基本排序:归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
(2)实例:



(3)用java实现
importjava.util.Arrays; publicclassmergingSort{ inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51}; publicmergingSort(){ sort(a,0,a.length-1); for(inti=0;i<a.length;i++) System.out.println(a[i]); } publicvoidsort(int[]data,intleft,intright){ //TODOAuto-generatedmethodstub if(left<right){ //找出中间索引 intcenter=(left+right)/2; //对左边数组进行递归 sort(data,left,center); //对右边数组进行递归 sort(data,center+1,right); //合并 merge(data,left,center,right); } } publicvoidmerge(int[]data,intleft,intcenter,intright){ //TODOAuto-generatedmethodstub int[]tmpArr=newint[data.length]; intmid=center+1; //third记录中间数组的索引 intthird=left; inttmp=left; while(left<=center&&mid<=right){ //从两个数组中取出最小的放入中间数组 if(data[left]<=data[mid]){ tmpArr[third++]=data[left++]; }else{ tmpArr[third++]=data[mid++]; } } //剩余部分依次放入中间数组 while(mid<=right){ tmpArr[third++]=data[mid++]; } while(left<=center){ tmpArr[third++]=data[left++]; } //将中间数组中的内容复制回原数组 while(tmp<=right){ data[tmp]=tmpArr[tmp++]; } System.out.println(Arrays.toString(data)); } }

8、基数排序


(1)基本思想:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。

(2)实例:




(3)用java实现importjava.util.ArrayList;

importjava.util.List;

publicclassradixSort{

inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,101,56,17,18,23,34,15,35,25,53,51};

publicradixSort(){

sort(a);

for(inti=0;i<a.length;i++)

System.out.println(a[i]);

}

publicvoidsort(int[]array){

//首先确定排序的趟数;

intmax=array[0];

for(inti=1;i<array.length;i++){

if(array[i]>max){

max=array[i];

}

}

inttime=0;

//判断位数;

while(max>0){

max/=10;

time++;

}

//建立10个队列;

List<ArrayList>queue=newArrayList<ArrayList>();

for(inti=0;i<10;i++){

ArrayList<Integer>queue1=newArrayList<Integer>();

queue.add(queue1);

}

//进行time次分配和收集;

for(inti=0;i<time;i++){

//分配数组元素;

for(intj=0;j<array.length;j++){

//得到数字的第time+1位数;

intx=array[j]%(int)Math.pow(10,i+1)/(int)Math.pow(10,i);

ArrayList<Integer>queue2=queue.get(x);

queue2.add(array[j]);

queue.set(x,queue2);

}

intcount=0;//元素计数器;

//收集队列元素;

for(intk=0;k<10;k++){

while(queue.get(k).size()>0){

ArrayList<Integer>queue3=queue.get(k);

array[count]=queue3.get(0);

queue3.remove(0);

count++;

}

}

}

}

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐