標籤:pre tmp shell out shell排序 blog 序列 儲存 元素
代碼如下:
public class ShellSort {public static void sellSort(DataWrap [] data){System.out.println("開始排序:");int length = data.length;//h變數儲存可變增量int h = 1;//按照h*3+1得到增量序列的最大值while(h <=length/3){h = h*3+1;}while(h >0){System.out.println("===h的值:"+h+"===");for(int i = h;i < length;i++){//當整體後移時,保證data[i]的值不會丟失DataWrap tmp = data[i];//i索引處的值已經比前面所有值都大,表明已經有序,無需插入//(i-1索引之前的資料已經有序的,i-1索引處元素的值就是最大)if(data[i].compareTo(data[i-h]) < 0){int j = i-h;//整體後移h格for( ;j >= 0 && data[j].compareTo(tmp) >0 ;j-=h){data[j+h] = data[j];}//最後將tmp的值插入合適的位置data[j+h] = tmp;}System.out.println(java.util.Arrays.toString(data));}h = (h-1)/3;}}public static void main(String[] args) {DataWrap[] data = {new DataWrap(21, ""),new DataWrap(30, ""),new DataWrap(49, ""),new DataWrap(30, ""),new DataWrap(16, ""),new DataWrap(9, ""),new DataWrap(-16, "")};System.out.println("排序之前:\n" + java.util.Arrays.toString(data));sellSort(data);System.out.println("排序之後:\n" + java.util.Arrays.toString(data));}}
java Shell排序