Bootstrap

【排序算法】桶排序

不能排序负数,适合数据较小但数据量较大的时候使用。
  • 定义了0-9十个桶,先排序个位,向高位排序
  • 首先,拿到数值后,先看个位,个位是几就放到对应的桶,以队列的形式进行排列。
  • 从0-9取出数据,先进来的先取走,依次取出
  • 从个位到高位依次进行上述操作。
时间复杂度:O(Kn),K值不能省。运行次数为最大位数×2n
import java.util.Arrays;

public class RadixSort {
	public static void main(String[] args) {
		int[] arr = {512,77,40,21,809,38,15,6};
		sort(arr);
		System.out.println(Arrays.toString(arr));
	}
	
	public static void sort(int[] arr) {
		
		// 定义0-9对应的桶
		int[][] bucket = new int[10][arr.length];
		// 定义桶记录工具
		int[] elementCount = new int[10];
		// 获取最大数值的位数
		int max = arr[0];
		for(int x : arr) {
			if(x>max) {
				max=x;
			}
		}
		// 转换成字符串,计算字符串的长度
		int maxLength = (max+"").length();
		
		// n 辅助计算位数
		int n =1;
		// 循环放入取出maxLength次
		for(int h = 0;h<maxLength;h++) {
			// 放入
			for(int i= 0;i<arr.length;i++) {
				// 获取个位数值element,也代表要放到哪个桶
				int element = arr[i]/n%10;
				// 读取桶记录elementCount当中的数据
				int count = elementCount[element];
				// 放入数据
				bucket[element][count] = arr[i];
				// 放入后对应的桶记录elementCount+1
				elementCount[element]++;
			}
			// 取出
			// 记录取出的数据写回数组的位置
			int index = 0;
			for(int i =0;i<elementCount.length;i++) {
				// 读取桶记录中的数值,决定对应桶当中能取出多少数值
				if(elementCount[i]!=0) {
					for(int j = 0;j<elementCount[i];j++) {
						arr[index++]=bucket[i][j];
					}
				}
				// 清空桶记录
				elementCount[i]=0;
			}
			n*=10;
		}
	}
}

;