java实现基数排序

package com.ycit.sortSelect;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 江鹏飞
 *	基数排序
 *	思路: 1.找到数组中的最大数
 *		 2.求最大数的位数
 *		 3.创建一个二维数组(一个数组嵌套十个数组)
 *		 4.依次把 个位,十位,百位,数 放入相应的数组 再进行收集
 */
public class BasicSort {
	public void basicSort(int a[]){
		//拿到数组的最大值
		int max=0;	
			for(int i=0;i<a.length;i++){
				if(a[i]>max){
					max=a[i];
				}
			}
		//求最大位的个数
		int times=0;
		while(max>0){
			max = max/10;
			times++;
		}
		//创建一个二维数组
		List<ArrayList> queen = new ArrayList<ArrayList>();
//		一个数组嵌套十个数组
		for(int i = 0;i<10;i++){
			ArrayList q = new ArrayList<>();
			queen.add(q);
		}
		for(int i=0;i<times;i++){
			//遍历元数组
			for(int j = 0;j<a.length;j++){
				//           限制位数							求所在位数
				int x = a[j]%(int)Math.pow(10, i+1)/(int)Math.pow(10, i);
				ArrayList q = queen.get(x);
				q.add(a[j]);
			}
			//进行收集
			int count=0;
			for(int z=0;z<10;z++){
				while(queen.get(z).size()>0){
					ArrayList<Integer> c = queen.get(z);
					a[count]=c.get(0);
					c.remove(0);
					count++;
				}
			}
		}		
	}
	public static void main(String[] args){
		BasicSort basicSort = new BasicSort();
		int [] a = {136,2,6,8,9,2,8,11,23,56,34,90,89,29,145,209,320,78,3};
		basicSort.basicSort(a);
		for(int n:a){
			System.out.print(" "+n);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40068214/article/details/89406250