您的位置:首页 > 编程语言 > Java开发

排序算法java 二 --基数排序、归并排序

2016-05-05 20:56 477 查看
1、基数排序----基本实现思想: 首先判断数组中数据最大的位数,然后比较个位上的数字,进行排序,然后比较其他位上的数字,依次进行排序。

/**
* 基数排序
*/
public static void radixSort(int []array){

int max = array[0];//找最大值
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}

int time = 0;//确定几位数字
while (max > 0) {
max /= 10;
time++;
}

List<ArrayList<Integer>> list = new ArrayList<>();//存储的十个桶用来存储0-9的数字的集合
for (int i = 0; i < 10; i++) {
list.add(new ArrayList<Integer>());
}

//按照各个位数进行排序
for (int i = 0; i < time; i++) {//最大数位数即循环次数
for (int j = 0; j < array.length; j++) {
//取到当前这个数对应位置的一位数
int a = array[j] / pow(i);
int b = a % 10;//求各个位上的数字
list.get(b).add(array[j]);
}
//各个位上的数进行排序
int n = 0;
for( ArrayList<Integer> arrayList : list){

if (arrayList.size() != 0) {

for(Integer inner : arrayList){

array
= inner.intValue();//拆箱操作
n++;
}
arrayList.clear();
}
}
}
System.out.println("------" + Arrays.toString(array));
}
private static int pow(int n){//用来求10的n次方,也可调用Math.pow(10,n);
int value = 1;
for (int i = 0; i < n; i++) {
value *= 10;
}
return value;
}


2、归并排序,不要看代码长,理解起来相对简单.gap是1、2、4、8...变化的,符合两个数组合并后的数组元素个数的变化。归并排序,首先两两一组比较排序,然后相邻的第一个组元素和第二个组元素比较排序合并成一个数组,依次进行。

/**
* 归并排序
*/
public static void mergeSort(int []array){

//前一个有序组合
ArrayList<Integer> listLeft = new ArrayList<>();
//后一个有序组合
ArrayList<Integer> listRight = new ArrayList<>();
//两个有序组合合并的结果
ArrayList<Integer> list = new ArrayList<>();

for (int gap = 1; gap < array.length; gap = gap * 2) {

for (int i = 0; i < array.length; i++) {

if (listLeft.size() < gap) {

listLeft.add(array[i]);
}else {
if (listRight.size() < gap) {

listRight.add(array[i]);
}
}
if (listLeft.size() == gap && listRight.size() == gap || 									(listLeft.size() == gap && listRight.size() < gap && i == array.length - 1)) {

switchArray(listLeft, listRight, list);

listLeft.clear();
listRight.clear();
}
}
for (int j = 0; j <list.size(); j++) {

array[j] = list.get(j);

}
listLeft.clear();
listRight.clear();
list.clear();
System.out.println(Arrays.toString(array));
}

}
private static void switchArray(ArrayList<Integer> listLeft,ArrayList<Integer> listRight,ArrayList<Integer> list ){

int m = 0;
int n = 0;
while (m < listLeft.size() && n < listRight.size()) {

while(m < listLeft.size() && n < listRight.size() && listLeft.get(m) < listRight.get(n)){

list.add(listLeft.get(m));
m++;
}

while (n < listRight.size() && m < listLeft.size() && listLeft.get(m) >= listRight.get(n)) {

list.add(listRight.get(n));
n++;
}
}

while (m < listLeft.size()) {//两个数组比较合并后剩余的元素依次添加到集合中,合并成一个数组

list.add(listLeft.get(m));
m++;
}

while (n < listRight.size()) {

list.add(listRight.get(n));
n++;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: