算法:两种希尔排序算法
1 /** 2 * 希尔排序 3 * 不同步长的算法 4 * @author mackxu 5 * 6 */ 7 class ShellSort { 8 private int[] a = {5,2,4,3,1}; 9 private int nElems = 5; 10 11 public ShellSort() { 12 13 } 14 15 public void display() { 16 for(int elem : a) { 17 System.out.print(elem + " "); 18 } 19 System.out.println(); 20 } 21 /** 22 * 外循环确定步长大小 23 * 中循环 24 * 内循环 25 */ 26 public void shell_sort() { 27 int in, temp; 28 for (int gap = nElems/2; gap>0; gap/=2) { 29 for (int out=gap; out<nElems; out++) { 30 temp = a[out]; //待排的元素 31 in = out; 32 //while循环中的两个判断条件 33 while(in>gap-1 && a[in-gap]>temp){ 34 a[in] = a[in-gap]; 35 in -= gap; 36 } 37 a[in] = temp; 38 } 39 } 40 41 } 42 43 public void shell_sort2() { 44 int out, in; 45 int temp; 46 47 //获取最大步长 48 //可取值有4、13、40、121、364、1093.... 49 int gap = 1; 50 while(gap<=nElems/3) 51 gap = gap*3 + 1; 52 while(gap>0) { 53 for(out=gap; out<nElems; out++) { 54 temp = a[out]; //待排的元素 55 in = out; 56 while(in>gap-1 && a[in-gap]>=temp) { 57 a[in] = a[in-gap]; //值大的后移, 腾出位置,等待填充 58 in -= gap; 59 } 60 a[in] = temp; //找到合适的位置,填充进去 61 } 62 gap = (gap-1)/3; //改变步长 63 } 64 65 } 66 }