import java.util.Arrays;
/**
* Created by Administrator on 2017/8/2.
*/
public class shellSort_insert {
public static void main(String args[]) {
int[] arr = { 6, 9, 1, 3, 1, 2, 2, 5, 6, 1, 3, 5, 9, 7, 2, 5, 6, 1, 9 };
//[1, 1, 1, 1, 2, 2, 2, 3, 3, 5, 5, 5, 6, 6, 6, 7, 9, 9, 9]
shellSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
/*算法思想:
* 1.将待排序的数组按照步长gap(初始gap=len/2)进行分组,然后按照直接插入排序方法进行排序
* 2.每次gap 折半,循环上述操作,当gap为1时,利用直接插入完成排序*/
/*时间复杂度:O(n^1.3)
* 空间复杂度:O(1)
* 稳定性:不稳定
* */
private static void shellSort(int[] arr, int start, int end) {
int gap = (end + 1)/2;
while (gap>=1) {
for (int i = 0; i<gap; i++) {
for (int j = gap; j<=end; j+=gap) {//直接插入排序
while (j-gap>=0 && arr[j]<arr[j-gap]) {
swap(arr,j,j-gap);
j = j-gap;
}
}
}
gap = gap/2;
}
}
private static void swap(int[] arr, int start, int end) {
int tmp = arr[start];
arr[start] = arr[end];
arr[end] = tmp;
}
}
八大排序算法之-希尔排序 java代码
最新推荐文章于 2022-08-19 11:29:36 发布