基数排序(桶排序)
package A;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class JosePhu {
public static void main(String[] args) {
Method method=new Method();
//int[] a={53,3,542,748,14,214};
int[] a={123,9,0,0,123,345345353,35,4,6,76,87,4,3};
method.radixSort(a);
System.out.println(Arrays.toString(a));
}
}
package A;
import java.util.Arrays;
public class Method {
public void radixSort(int[] a){//速度很快,比前面的快排什么的都要快,但是是以内存换时间,能测试的数据具体看电脑配置
int max=a[0];
for (int i = 0; i < a.length; i++) {
if (a[i]>max){
max=a[i];
}
}//for find the maximum
int maxlength=(max+"").length();//为了使max变成一个字符串
int[][] bucket=new int[10][a.length];
int[] count=new int[10];
for (int i = 0,n=1; i < maxlength; i++,n*=10) {
for (int j = 0; j < a.length; j++) {//pick up
int temp=a[j]/n%10;
bucket[temp][count[temp]]=a[j];
count[temp]++;//the record is for easy access
}
int index=0;
for (int k = 0; k < count.length; k++) {//put in
if (count[k]!=0){
for (int l = 0; l < count[k]; l++) {
a[index]=bucket[k][l];
index++;
}
}
count[k]=0;
}
}
/*//one
for (int j = 0; j < a.length; j++) {//pick up
int temp=a[j]%10;
bucket[temp][count[temp]]=a[j];
count[temp]++;//the record is for easy access
}
int index=0;
for (int k = 0; k < count.length; k++) {//put in
if (count[k]!=0){
for (int l = 0; l < count[k]; l++) {
a[index]=bucket[k][l];
index++;
}
}
count[k]=0;//count是记录的,所以要置零。bucket一直被赋值,每赋一个值,它原先的就被替换了,所以不用置零
}
System.out.println("第一轮,对个位数排序处理a="+ Arrays.toString(a));
//two
for (int j = 0; j < a.length; j++) {
int temp=a[j]/10%10;
bucket[temp][count[temp]]=a[j];
count[temp]++;
}
index=0;
for (int k = 0; k < count.length; k++) {
if (count[k]!=0){
for (int l = 0; l < count[k]; l++) {
a[index]=bucket[k][l];
index++;
}
}
count[k]=0;
}
System.out.println("第二轮,对个位数排序处理a="+ Arrays.toString(a));
for (int j = 0; j < a.length; j++) {
int digiOfElement=a[j]/100%10;
bucket[digiOfElement][count[digiOfElement]]=a[j];
count[digiOfElement]++;
}
index=0;
for (int k = 0; k < count.length; k++) {
if (count[k]!=0){
for (int l = 0; l < count[k]; l++) {
a[index]=bucket[k][l];
index++;
}
}
count[k]=0;
}
System.out.println("第san轮,对个位数排序处理a="+ Arrays.toString(a));*/
}
}
这一路,灯火通明