ShellSort

 

复制代码
package Sort;

import java.util.Arrays;
/**
 * 希尔排序(Shellsort)也是一种插入排序,它是简单插入排序经过改进之后的一个更高效的版本,也称为缩小增量排序
 * 希尔排序:非稳定排序算法
 *
 * */

public class ShellSort {
    public static void main(String[] args) {
        int[] arr = new int[]{8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        shellSort2(arr);
        System.out.println("  " + Arrays.toString(arr));

    }
    public static void shellSort(int[] arr) {
        int length = arr.length;
        int temp;
        for (int step = length / 2; step >= 1; step /= 2) { // 分组
            for (int i = step; i < length; i++) { // 遍历各个组
                temp = arr[i];
                int j = i - step;  // 找到组内的其他元素
                while (j >= 0 && arr[j] > temp) {
                    arr[j + step] = arr[j];
                    j -= step;
                }
                arr[j + step] = temp;
            }
        }
    }

    public static void shellSort2(int[]arr){
        for (int step = arr.length/2; step >=1 ; step/=2) { // 步长
            //i:代表即将插入的元素角标,作为每一组比较数据的最后一个元素角标
            //j:代表与i同一组的数组元素角标
            for (int i = step; i < arr.length; i++) {
                for (int j = i-step; j >=0 ; j-=step) {
                    if (arr[j]>arr[j+step]){
                        int temp = arr[j];
                        arr[j] = arr[j+step];
                        arr[j+step] = temp;
                    }
                }
            }
        }
    }

}
复制代码

 

  

posted @   坤坤无敌  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示