import java.util.Arrays;import java.util.Random;publicclassShellSort{publicstaticvoidmain(String[] args){// int[] arr = { 1, 1, 78, 4, 9, 1, 23, -5, 4, 3, 76, 12 };// 随机生成数组int[] arr =newint[8];
Random rand =newRandom();for(int i =0; i < arr.length; i++){
arr[i]= rand.nextInt(1000);}
System.out.println("排序前:"+ Arrays.toString(arr));shellSort(arr);
System.out.println("排序后:"+ Arrays.toString(arr));}publicstaticvoidshellSort(int[] arr){for(int gap = arr.length /2; gap >0; gap /=2){for(int i = gap; i < arr.length; i++){int j = i;int temp = arr[i];// 找位置while(j-gap >=0&& temp < arr[j-gap]){
arr[j]= arr[j-gap];
j -= gap;}// 此时的j 就是那个合适的位置了
arr[j]= temp;}}}}
基数排序算法
import java.util.Arrays;publicclassRadixSort{publicstaticvoidmain(String[] args){int[] arr ={-7,-335,0,-90,1,123,1,78,4,64,2204,9,0,1,23,12};
System.out.println("排序前:"+ Arrays.toString(arr));radixSort(arr);
System.out.println("排序后:"+ Arrays.toString(arr));}publicstaticvoidradixSort(int[] arr){// 定义20个桶,正负数皆可int[][] bucket =newint[20][arr.length];// 每个桶的指针int[] counts =newint[20];// 求数组最大值的位数int max = arr[0];for(int i =1; i < arr.length; i++){if(max < arr[i]){
max = arr[i];}}int len =(max +"").length();for(int i =0, n =1; i < len; i++, n *=10){for(int j =0; j < arr.length; j++){int rem =(arr[j]/n)%10;// 负数用前10个桶,正数用后10个桶
rem +=10;
bucket[rem][counts[rem]++]= arr[j];}int index =0;// 遍历所有的桶将数据取出,放入数组for(int k =0; k < counts.length; k++){if(counts[k]>0){for(int p =0; p < counts[k]; p++){
arr[index++]= bucket[k][p];}
counts[k]=0;}}}}}