如何用一句话清晰明了的介绍shell排序呢?
从第一个元素开始,对间距为h的元素进行排序,排好后再从第二个元素与间隔h的元素开始往后排......直到排到第h个元素,这样就能保证所有元素都按间隔h排了一遍,保证元素与间隔h的元素之间是有序的。然后按h = (h-1)/3不断缩小h再排序一遍,缩小一次排一遍,一点点缩小间隔到保证间隔为1的元素之间都是有序的。
这样较直接插入排序而言,减少了数组元素的移动次数。
======================================================
package sort_1; public class ShellSort { public static void shellSort(DataWrap[] data) { int arrayLength = data.length; int h = 1; while(h<arrayLength/3) h = h*3 -1; while(h>0) { System.out.println("===的h值:"+h+"==="); for(int i = h;i<arrayLength;i++) { DataWrap temp = data[i]; if(data[i].compareTo(data[i-h])<0) { int j = i - h; for(;j>=0&&data[j].compareTo(temp)>0;j-=h) { data[j+h] = data[j]; } data[j+h]=temp; } System.out.println(java.util.Arrays.toString(data)); } h = (h-1)/3; } } public static void main(String[] args) { DataWrap[] data = new DataWrap[]{ new DataWrap(2,""), new DataWrap(5,""), new DataWrap(1,""), new DataWrap(3,""), new DataWrap(6,""), new DataWrap(9,""), new DataWrap(8,""), new DataWrap(4,""), new DataWrap(7,""), new DataWrap(0,""), new DataWrap(11,""), new DataWrap(10,""), }; ShellSort.shellSort(data); // System.out.println(java.util.Arrays.toString(data)); } }