开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第二十二天,点击查看活动详情
四、希尔排序
基本思想
希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰 被分成一组,算法便终止
分析
初始数组 {8,9,1,7,2,3,5,4,6,0}
- 希尔排序时, 对有序序列在插入时采用交换法, 并测试排序速度.
- 希尔排序时, 对有序序列在插入时采用移动法, 并测试排序速度
交换法:
import java.util.Arrays;
/**
* @author Kcs 2022/9/3
*/
public class ShellSort {
public static void main(String[] args) {
int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
shellSort(arr);
}
/**
* 希尔排序
*/
public static void shellSort(int[] arr) {
int temp = 0;
int count = 0;
// 循环处理 希尔排序
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < arr.length; i++) {
//遍历各组中所有的元素
for (int j = i - gap; j >= 0; j -= gap) {
//当前元素大于加上步长后的元素,则进行交换
if (arr[j] > arr[j + gap]) {
temp = arr[j];
arr[j] = arr[j + gap];
arr[j + gap] = temp;
}
}
}
System.out.println("第" + (++count) + "轮希尔排序结果:" + Arrays.toString(arr));
}
}
}
移步法
import java.util.Arrays;
/**
* @author Kcs 2022/9/3
*/
public class ShellSort {
public static void main(String[] args) {
int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
shellSort(arr);
System.out.println("交换法:" + Arrays.toString(arr));
shellSort2(arr);
System.out.println("移位法:" + Arrays.toString(arr));
}
/**
* 移位法
* @param arr
*/
public static void shellSort2(int[] arr) {
for (int gap = arr.length / 2; gap > 0; 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;
}
}
}
}
}