希尔排序
前面已经知道了插入排序,明白插入排序的原理,不断比较来交换相邻的元素,这样的话效率不高,为此希尔排序,在插入排序上做出了改进,通过间隔增量来比较并交换元素,这样可以减少比较交换的次数。
1 package com.yunche.testsort; 2 3 import java.util.Arrays; 4 5 /** 6 * @ClassName: ShellSort 7 * @Description: 8 * @author: yunche 9 * @date: 2018/11/30 10 */ 11 public class ShellSort { 12 public static void main(String[] args) { 13 int[] a = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0}; 14 new ShellSort().sort(a); 15 System.out.println(Arrays.toString(a)); 16 }/*Output: 17 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 18 */ 19 20 private void sort(int[] a) { 21 int len = a.length; 22 for (int gap = len >> 1; gap > 0; gap = gap >> 1) { 23 24 for (int i = gap; i < len; i++) { 25 for (int j = i; j > gap - 1; j = j - gap) { 26 //使当前元素找到属于自己的位置 27 if (a[j] < a[j - gap]) { 28 int temp = a[j]; 29 a[j] = a[j - gap]; 30 a[j - gap] = temp; 31 } 32 } 33 } 34 } 35 } 36 }
可以和前面的插入排序的代码对比,可以发现希尔排序内部就是插入排序的代码,上面的代码24行开始的两个循环,和插入排序代码其实是一样的,将 gap 替换成 1 两者就一样了。
插入排序:
for (int i = 1; i < len; i++) { for (int j = i; j > 0; j--) { //使当前元素找到属于自己的位置 if (a[j] < a[j - 1]) { int temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; } } }