1.计数排序:
import java.util.Arrays;
public class MM {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a={3, 1, 6, 0, 3, 0, 1, 5, 3, 6};
int max=getMax(a);
a=mySort(a,max);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
private static int[] mySort(int[] a, int max) {
// TODO Auto-generated method stub
int[] b=new int[max+1];
int[] c=new int[a.length];
Arrays.fill(b, 0);
for(int i=0;i<a.length;i++)
b[a[i]]++;
for(int i=1;i<b.length;i++)
b[i]=b[i]+b[i-1];
for(int i=a.length-1;i>=0;i--){
int temp=a[i];
c[b[temp]-1]=temp;
b[temp]--;
}
return c;
}
private static int getMax(int[] a) {
// TODO Auto-generated method stub
int max=a[0];
for(int i=1;i<a.length;i++){
if(a[i]>a[0])
max=a[i];
}
return max;
}
}
2.基数排序:
import java.util.Arrays;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a={3,2,3,2,5,333,45566,2345678,78,990,12,432,56};
int time=countDigit(a);
radixSort(a,time);
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
private static void radixSort(int[] a, int time) {
// TODO Auto-generated method stub
int len_a=a.length;
int[] b=new int[10];//0-9,10个数字
int[] c=new int[len_a];//作用是:更新int[] a
int divide=1;
for(int i=0;i<time;i++){
c=Arrays.copyOf(a, len_a);
Arrays.fill(b, 0);
for(int j=0;j<len_a;j++){
int temp=(c[j]/divide)%10;//求各个位上的数
b[temp]++;
}
for(int j=1;j<b.length;j++)
b[j]=b[j]+b[j-1];
for(int j=len_a-1;j>=0;j--){
int temp=(c[j]/divide)%10;
a[b[temp]-1]=c[j];
b[temp]--;
}
divide=divide*10;
}
}
private static int countDigit(int[] a) {
// TODO Auto-generated method stub
int max=a[0];
for(int i=1;i<a.length;i++){
if(a[i]>max)
max=a[i];
}
String s=max+"";
return s.length();
}
}
3.桶排序:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double[] a={0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12,0.23, 0.68 };
bucketSort(a);
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
private static void bucketSort(double[] a) {
// TODO Auto-generated method stub
ArrayList[] b=new ArrayList[a.length];
for(int i=0;i<a.length;i++){
int temp=(int)Math.floor(10*a[i]);
if(b[temp]==null)
b[temp]=new ArrayList();
b[temp].add(a[i]);
}
int count=0;
for(int i=0;i<b.length;i++){
if(b[i]!=null){
Collections.sort(b[i]);
Iterator iter=b[i].iterator();
while(iter.hasNext()){
a[count++]=(Double)iter.next();
}
}
}
}
}