归并排序

归并排序

思想:采用分治思想。
分:将要排序的数组划分成长度为1的小数组
治:合并小数组进行排序
代码:

package com.practice;

import java.util.Arrays;

public class GuiBingSort {
    public static void main(String[] args) {
        int[] array = new int[]{3, 2, 6, 5, 9, 8, 0, 7};
        int[] temp = new int[array.length];//创建一个临时数组用来存储排好序的元素
        GBSort( array, 0, array.length-1, temp );
        System.out.println(Arrays.toString( array ) );
    }
    //分:将数组分成长度为一的小数组
    private static void GBSort(int[] array, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            GBSort( array, left, mid, temp );
            GBSort( array, mid + 1, right, temp );
            merge( array, left, mid, right,temp );
        }
    }
   //治:对分好组的子序列进行排序
    private static void merge(int[] array, int left, int mid, int right,int[] temp) {
        int i = left;
        int j = mid + 1;
        int k=0;
        while (i<=mid&&j<=right){
            if(array[i]<=array[j]){
                temp[k++]=array[i++];
            }else{
                temp[k++]=array[j++];
            }
        }
        while (i<=mid) {
            temp[k++]=array[i++];
        }
        while (j<=right){
            temp[k++]=array[j++];
        }
        k=0;
        while (left<=right){
            array[left++]=temp[k++];
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值