八大排序算法之基数排序

来源:互联网 发布:淘宝店怎么提高访问量 编辑:程序博客网 时间:2024/05/11 04:48
package com.zyg.sort;public class RadixSortAlgorithm{// 基数排序,len为数组长度,maxRadix为数组中数的最大位数public static void radixSort(int a[], int len, int maxRadix){// 定义二维辅助数组int temp[][] = new int[10][len];// 当前排序的位数,初始状态为个位int partition = 1;// 依次从个位数到最高位排序for (int index = 0; index < maxRadix; index++){for (int i = 0; i < len; i++){// 根据排序位上的数字放入二维数组,数字取值为0-9int loc = (a[i] / partition) % 10;temp[loc][i] = a[i];}// 收集数组CollectElement(a, temp);// 排序位数左移partition = partition * 10;}}// 收集数组public static void CollectElement(int a[], int temp[][]){int index = 0;for (int i = 0; i < temp.length; i++){for (int j = 0; j < temp[0].length; j++){// 如果辅助数组中元素值大于零,将其加入数组if (temp[i][j] > 0)a[index++] = temp[i][j];// 重置辅助数组temp[i][j] = 0;}}}// 合并数组public static void mergeArray(int a[], int left[], int right[], int len){int index = 0;// 负数数组还原,并进行倒转for (int i = left.length - 1; i >= 0; i--){a[index] = -left[i];index++;}// 数组中零for (int i = 0; i < len - left.length - right.length; i++){a[index] = 0;index++;}// 加入正数数组for (int i = 0; i < right.length; i++){a[index] = right[i];index++;}}// 打印数组public static void printArray(int a[]){for (int i = 0; i < a.length; i++){System.out.println(a[i]);}}public static void main(String[] args){// 定义初始化数组int a[] ={ -4, 3, 6, 7, 33, 0, 90, 0, 777, 50 };// 数组长度int len = a.length;// 负数数组和正数数组int left[], right[];// 数组中负数和正数个数int negativeNum = 0, positiveNum = 0;for (int i = 0; i < len; i++){if (a[i] < 0)negativeNum++;if (a[i] > 0)positiveNum++;}// 初始化负数数组和正数数组left = new int[negativeNum];right = new int[positiveNum];int j = 0, k = 0;for (int i = 0; i < len; i++){// 负数数组赋值,并取其绝对值if (a[i] < 0){left[j] = -a[i];j++;}// 正数数组if (a[i] > 0){right[k] = a[i];k++;}}// 负数数组基数排序radixSort(left, left.length, 3);// 正数数组基数排序radixSort(right, right.length, 3);// 将数组进行合并mergeArray(a, left, right, len);// 打印数组printArray(a);}}

0 0
原创粉丝点击