写一个希尔排序代码java要有注释
public class ShellSort { public static void shellSort(int[] arr) { int n = arr.length; // 定义增量gap,并逐步缩小增量 for (int gap = n / 2; gap > 0; gap /= 2) { // 对各个分组进行插入排序 for (int i = gap; i < n; i++) { int j = i; int temp = arr[j]; // 插入排序 if (arr[j - gap] > temp) { while (j - gap >= 0 && arr[j - gap] > temp) { arr[j] = arr[j - gap]; j -= gap; } arr[j] = temp; } } } }
public static void main(String[] args) {
int[] arr = {3, 5, 2, 8, 7, 1, 4, 6};
shellSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
} /* 输出结果为: 1 2 3 4 5 6 7 8 */
原文地址: https://www.cveoy.top/t/topic/bnCB 著作权归作者所有。请勿转载和采集!