希尔排序和归并排序

希尔排序

/**
 * @author:Xiao Chenglong
 * @Date:2021/5/17 希尔排序
 * 就是插入排序的改良版,减少计算时间
 **/
public class ShellSort {

    public static void sort(int[] arr) {
        int gap= arr.length/2;

        int current;

        while (gap > 0) {

            for (int i = gap; i < arr.length; i++) {
                current=arr[i];
                int preindex= i-gap;
                while (preindex>=0 && arr[preindex]>current) {
                    arr[preindex + gap] = arr[preindex];
                    preindex = preindex - gap;
                }
                arr[preindex+gap]=current;
            }

            gap=gap/2;
        }
    }

    public static void main(String[] args) {
        int arr[] = new int[]{1, 66, 4, 21, 7, 7, 3, 5, 9, 44, 56, 3, 6, 11, 15, 34, 18, 22};
        sort(arr);
        for (int a : arr) {
            System.out.print(a + " ");
        }
        System.out.println();
    }
}

归并排序

/**
 * @author:Xiao Chenglong
 * @Date:2021/5/17 归并排序
 **/
public class MergeSort {

    // 两个核心函数,sort(分),merge(合)
    private static void Sort(int[] a, int left, int right) {
        if (left >= right)
            return;

        int mid = (left + right) / 2;
        //二路归并排序里面有两个Sort,多路归并排序里面写多个Sort就可以了
        Sort(a, left, mid);
        Sort(a, mid + 1, right);
        merge(a, left, mid, right);

    }

    private static void merge(int[] a, int left, int mid, int right) {
		
		// 定义一个新的数组保存
        int[] tmp = new int[a.length];
        int r1 = mid + 1;
        int cIndex = left;
        // int tIndex = left;
        int tIndex = 0;
        // 逐个归并
        while (left <= mid && r1 <= right) {
            if (a[left] <= a[r1])
                tmp[tIndex++] = a[left++];
            else
                tmp[tIndex++] = a[r1++];
        }
        // 将左边剩余的归并
        while (left <= mid) {
            tmp[tIndex++] = a[left++];
        }
        // 将右边剩余的归并
        while (r1 <= right) {
            tmp[tIndex++] = a[r1++];
        }

        // 把 temp 拷贝到原数组
        for (int i = 0; i < tIndex ; i++) {
            a[cIndex+i]=tmp[i];
        }
    }


    public static void main(String[] args) {
        int arr[] = new int[]{1, 66, 4, 21, 7, 7, 3, 5, 9, 44, 56, 3, 6, 11, 15, 34, 18, 22};
        Sort(arr, 0, arr.length - 1);
        for (int a : arr) {
            System.out.print(a + " ");
        }
        System.out.println();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肖大仙~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值