桶排序的java实现
2015-09-07 09:01
766 查看
package com.edu.hpu.sort.bucket; import java.util.LinkedList; import java.util.List; import com.edu.hpu.sort.Sort; /* 排序原理: 顺序从待排数组中取出数字,首先6被取出,然后把6入6号桶,这个过程类似这样:空桶[ 待排数组[ 0 ] ] = 待排数组[ 0 ] [6 2 4 1 5 9] 待排数组 [0 0 0 0 0 0 6 0 0 0] 空桶 [0 1 2 3 4 5 6 7 8 9] 桶编号(实际不存在) 顺序从待排数组中取出下一个数字,此时2被取出,将其放入2号桶,是几就放几号桶 [6 2 4 1 5 9] 待排数组 [0 0 2 0 0 0 6 0 0 0] 空桶 [0 1 2 3 4 5 6 7 8 9] 桶编号(实际不存在) 3,4,5,6省略,过程一样,全部入桶后变成下边这样 [6 2 4 1 5 9] 待排数组 [0 1 2 0 4 5 6 0 0 9] 空桶 [0 1 2 3 4 5 6 7 8 9] 桶编号(实际不存在) */ public class BucketSort extends Sort { private int range = 0; public BucketSort(int range) { this.range = range; } @Override public int[] doSort(int[] arr) { @SuppressWarnings("unchecked") // 构造辅助数组 List<Integer> [] aux = new LinkedList[range]; for(int i = 0; i < aux.length; i++){ aux[i] = new LinkedList<Integer>(); } for(int i = 0; i < arr.length; i++){ // 找打元素在桶中的位置,并将其添加 aux[arr[i]].add(arr[i]); } for(int i = 0, j = 0; i < aux.length && j < arr.length; i++){ for(int v : aux[i]){ arr[j] = v; j++; } } return arr; } public static void main(String[] args) { Sort sort = new BucketSort(10); sort.printOrder(new int []{4, 1, 3, 2, 6, 9, 9}); } }
相关文章推荐
- 打开MyEclipse10是时候提示:Could not create the view: An unexpected exception was thrown.
- Java基础知识强化18:抽象类、接口的区别 和 抽象类可以不实现接口的全部方法
- Eclilpse导入maven项目,无法自动构建为java项目的问题
- struts2开发流程
- Spring--JdbcTemplate
- 学习日志---哈夫曼树相关算法
- 基于XML的Spring AOP配置
- Java中的代码点和代码单元
- How to get session information in Spring MVC 3
- Spring MVC hello world annotation example
- 【springmvc+mybatis项目实战】杰信商贸-6.重点知识回顾
- SpringSecurity3.2.8翻译说明
- Eclipse与Git结合使用
- jdk各版本区别
- java集合类与并发包内的对象使用说明
- thinking in java 多态,接口,内部类,异常小结
- 【Java集合之二】Set集合
- eclipse 内存配置
- 异步ztree展现struts2后台数据集
- Something about how install Eclipse onto Ubuntu14.04