希爾排序百萬級數據比較,循環次數少反而性能更差?求解!!!

//(1)for (int i = gap; i < arr.length; i++) { 
//(2)for (int i = gap; i < arr.length; i+=gap) {
//  ???:這裏i++和i+=gap均可以,而且i+=gap循環次數更少,爲啥用了反而性能更差呢

/*
* * @desc 希爾排序 * 它是一種更高效的插入排序,也稱爲縮小增量排序。 * 產生緣由: * 因爲插入排序存在問題,當須要插入數最小時,後移的次數明顯增多,對效率有影響 * 基本思想: * 把記錄按下標的必定增量分組,對每組使用直接插入排序算法排序; * 隨着增量減小,每組包含的關鍵詞愈來愈多,當增量減至1時,整個文件恰被分紅一組,算法便終止 * * 案例: * {8, 9, 1, 7, 2, 3, 5, 4, 6, 0} * @Author xw * @Date 2019/9/5 */ public class ShellSort { public static void main(String[] args) { /*int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0}; shellSort2(arr); System.out.println("第1輪事後,arr=" + Arrays.toString(arr));*/ int[] arr = new int[8000000]; for (int i = 0; i < 8000000; i++) { arr[i] = new Random().nextInt(8000000); } System.out.println(LocalDateTime.now()); shellSort2(arr); System.out.println(LocalDateTime.now()); //System.out.println("arr=" + Arrays.toString(arr)); } /** * 移動法(推薦) * @param arr */ private static void shellSort2(int[] arr) { int j; int temp; for (int gap = arr.length / 2; gap > 0; gap /= 2) { // 第1輪 [8,3] [9,5] [1,4] [7,6][2,0] for (int i = gap; i < arr.length; i++) { // ???:這裏i++和i+=gap均可以,而且i+=gap循環次數更少,爲啥用了反而性能更差呢 j = i; temp = arr[j]; while (j - gap >= 0 && temp < arr[ j - gap]) { // 還沒找到 // 後移 arr[j] = arr[j - gap]; j -= gap; } arr[j] = temp; } } } }

 代碼:https://github.com/line007/jucdemo2/blob/master/src/main/java/com/line/datastructs/sort/ShellSort.java#L46-47java

gitee地址:https://gitee.com/linestyle007/jucdemo2git

博客地址:https://linestyle007.gitee.io/github

github地址:https://github.com/line007/jucdemo2算法

相關文章
相關標籤/搜索