看到插入排序眼前就浮现起小时候打扑克牌的情景,插入排序可能是玩牌经常用到的一种排序方法,思想很简单:
对一个将要排序的序列,从第二个元素开始,如果其小于前面元素,则将其插入到前面的元素中去,很自然地,前面的元素要进行后移,不断比较移动直到结束。
插入排序的优点是对于已经很有序的序列效率很高,因为只有很少的移动。希尔排序正是基于此对插入排序进行改进,算法思想是先取小块进行插入排序,然后对基本有序的小块继续插入排序。
public class ShellSort {
public static void main(String[] args) {
int[] array = { 49, 38, 65, 97, 76, 13, 27, 49, 55, 4 };
shellSort(array);
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
public static void shellSort(int[] arr) {
int length = arr.length;
int d = length;
int times = 0;
while (true) {
d = d / 2;
for (int i = 0; i < d; i++)
for (int j = i; j < length; j = j + d) {
int k;
int temp = arr[j];
for (k = j - d; k >= 0 && temp < arr[k]; k = k - d) {
arr[k + d] = arr[k];
}
arr[k+d] = temp;
}
times++;
System.out.println("第" + times + "趟排序结果:");
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
if (d == 1)
break;
}
}
}
最后打印结果为:
第1趟排序结果:
13 27 49 55 4 49 38 65 97 76
第2趟排序结果:
4 27 13 49 38 55 49 65 97 76
第3趟排序结果:
4 13 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97