package Sort;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
/*
希尔排序
*/
public class ShellSort {
public static void main(String[] args) {
/*int [] arr = new int[80000];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int)( Math.random() * 80000);
}*/
int [] arr = {8,9,1,7,2,3,5,4,6,0};
print(arr);
//时间测试: 8s
Date date1 = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh-mm-ss");
String strDate1 = simpleDateFormat.format(date1);
System.out.println("排序前的时间是"+strDate1);
//shellSort(arr);
shellSort02(arr);
Date date2 = new Date();
//SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-mm-dd hh-mm-ss");
String strDate2 = simpleDateFormat.format(date2);
System.out.println("排序后的时间是"+strDate2);
System.out.println("-------------------");
print(arr);
}
/*
[8,9,1,7,2,3,5,4,6,0]
第一轮:gap = arr.length / 2 --> 5,分成五组即[8,3],[9,5],[1,4],[7,6],[2,0]
交换,3 9 1 7 2 8 5 4 6 0
3 5 1 7 2 8 9 4 6 0
....................
即3 5 1 6 0 8 9 4 7 2
第二轮:gap = gap / 2 -- > 5 / 2 == 2, 分成两组[3,1,0,9,7] ,[5,6,8,4,2]
[0,1,3,7,9], [2,4,5,6,8]--->[2,1,4,3,5,7,6,9,8]
.....
*/
public static void shellSort(int [] arr){
int tmp = 0;
//gap 表示每一轮将所有元素分为几组
for(int gap = arr.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < arr.length && gap != 0; i++) {
for (int j = i - gap; j >= 0; j -= gap) {
//逐个比较各个分组内的元素的大小,把小的交换到左边,大的交换到右边
if (arr[j] > arr[j + gap]) {
tmp = arr[j];
arr[j] = arr[j + gap];
arr[j + gap] = tmp;
}
}
}
print(arr);
}
}
//希尔排序的优化算法,移位法
public static void shellSort02(int [] arr){
for(int gap = arr.length / 2; gap > 0; gap = gap / 2){
//从第gap个元素起,逐个对其所在的组进行插入排序
for(int i = gap; i < arr.length; i++){
int j = i;//记录插入的位置
int temp = arr[j];//记录需要移位插入的元素的值
if( arr[j] < arr[j - gap]){
while (j - gap >= 0 && temp < arr[j - gap]){
//移动
arr[j] = arr[j - gap];
j -= gap;
}
//当退出循环的时候
arr[j] = temp;//找到要插入的位置
}
}
}
}
public static void print(int [] array){
for (int i = 0; i < array.length; i++) {
System.out.printf("%d ",array[i]);
if(i % 50 == 0){
System.out.println();
}
}
System.out.println();
// System.out.println(count);
}
}