算法筆記六、希爾排序代碼

package com.hao.firstdemo.datastruct.sort;

import java.util.Arrays;

/**
 * @author haoxiansheng
 * @data 2020/5/7 23:00
 */
public class ShellSort {
    public static void main(String[] args) {
        int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        // 測試
        shellSort(arr);
        shellSort2(arr);
    }

    /**
     * 希爾排序交換法  這個時間比插入排序慢了
     *
     * @param arr
     * @return
     */
    public static int[] shellSort(int[] arr) {
        int temp = 0;
        int count = 1;
        // 分組
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < arr.length; i++) {

                // 遍歷各組中的元素 每組(gap個)
                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.printf("希爾排序交換第%d輪 爲=》%s", count, Arrays.toString(arr));
            System.out.println();
            count++;
        }
        return arr;
    }

    /**
     * 希爾排序移位法
     *
     * @param arr
     * @return
     */
    public static int[] shellSort2(int[] arr) {

        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            int temp = 0;
            int count = 1;
            for (int i = gap; i < arr.length; i++) {
                int j = i;
                temp = arr[i];
                if (arr[j] < arr[j - gap]) {
                    while (j - gap >= 0 && temp < arr[j - gap]) {
                        // 移動
                        arr[j] = arr[j - gap];
                        j -= gap;
                    }
                    // 當退出循環,就給temp找到插入位置 這可以優化
                    arr[j] = temp;
                }
            }
            System.out.printf("希爾排序位移第%d輪 爲=》%s", count, Arrays.toString(arr));
            System.out.println();
            count++;
        }
        return arr;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章