基数排序




public class RadixSort {
public static void main(String[] args) {
int[] a = { 123, 963, 234, 546, 361, 798, 479, 310, 617, 892 };

Display(a, "Before sort:");

a = radixSort(a);

Display(a, "After sort:");
}

public static int[] radixSort(int[] a) {
int[] b = new int[a.length];

for (int i = 0; i < a.length; i++)
b[i] = a[i];

for (int i = 1; i <= a.length; i++)
b = countSort(b, i);

return b;
}

public static int[] countSort(int[] a, int k) {
int[] b = new int[a.length];
int[] c = new int[10];

for (int i = 0; i < b.length; i++)
b[i] = 0;

for (int i = 0; i < c.length; i++)
c[i] = 0;

int s = 1;
for (int i = 0; i < k; i++)
s = s * 10;

int temp1 = 0;
for (int i = 0; i < a.length; i++) {
temp1 = a[i] % s;
temp1 = temp1 * 10 / s;

c[temp1] = c[temp1] + 1;
}

for (int i = 1; i < c.length; i++)
c[i] = c[i] + c[i - 1];

int temp2 = 0;
for (int i = a.length - 1; i >= 0; i--) {
temp1 = a[i];
temp2 = a[i] % s;
temp2 = temp2 * 10 / s;

b[c[temp2] - 1] = temp1;
c[temp2] = c[temp2] - 1;
}

return b;
}

public static void Display(int[] a, String str) {
System.out.println(str);
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + "  ");
System.out.println();
}

}



运行结果:

Before sort:
123  963  234  546  361  798  479  310  617  892 
After sort:
123  234  310  361  479  546  617  798  892  963 


另外的排序



public class RadixSort {
public static void main(String[] args) {
int[] a = { 1, 3, 42, 43, 75, 45, 15, 73, 72};
print.p(sort(a,2));
}

public static  int[] sort(int[] number,int len) {
int k = 0;
int n = 1;
int m = 1;
int[][] temp = new int[number.length][number.length];
int[] order = new int[number.length];
while (m <= len) {

//取个位数 1,2,3,5 n=1
//取十位数 0,1,4,7 n=10
for (int i = 0; i < number.length; i++) {
int lsd =(number[i] / n) % 10;
temp[lsd][order[lsd]] = number[i];
order[lsd]++;
}
//赋值
for (int i = 0; i < number.length; i++) {
if (order[i] != 0)
for (int j = 0; j < order[i]; j++) {
number[k] = temp[i][j];
k++;
}
order[i] = 0;
}
n *= 10;
k = 0;
m++;
}
return number;
}

}

运行如下:

1 3 15 42 43 45 72 73 75

你可能感兴趣的:(C++,c,C#,J#)