1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| package com.zyg.sort;
public class RadixSortAlgorithm { public static void radixSort(int a[], int len, int maxRadix) { int temp[][] = new int[10][len]; int partition = 1; <!--more--> for (int index = 0; index < maxRadix; index++) { for (int i = 0; i < len; i++) { int 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); } }
|