排序算法之归并排序

思路:归并排序是把一个无序的数组,分割成若干个小块,没快排序,整合,在排序,最后合成完成数组的过程。过程分为1.分割2.整合

图解:图片来自https://www.cnblogs.com/chengxiao/p/6194356.html


2个数组合成情况如下图所示:这里要把内容移动一个新的数组中,排序完成后再copy到原数组。



每次左右比较吧小的数放到新的数组中。

详细代码:

package rank;

public class MergeRank { // 合并排序
	public static void main(String[] args) {
		int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
		int[] temp = new int[arr.length];
		temp = sort(arr, 0, arr.length - 1, temp);
		for (int i = 0; i < temp.length; i++) {
			System.out.print(temp[i] + "--");
		}
	}

	/*
	 * sort 方法用于吧一个数组 分组,调用merge方法进行排序
	 */
	public static int[] sort(int[] arr, int left, int right, int[] temp) {
		int mid = (left + right) / 2;
		if (left < right) {
			sort(arr, left, mid, temp);// 左边多次调用 多次分组,使得左边有序
			sort(arr, mid + 1, right, temp);// 右边有序
			temp = merge(left, mid, right, arr, temp); // 排序 并合并合并
		}
		return temp;
	}

	public static int[] merge(int left, int mid, int right, int[] arr, int[] temp) {
		int i = left;
		int j = mid + 1;
		int num = 0;
		while (left <= mid && j <= right) {// 保证左右不越界
			if (arr[left] < arr[j]) {// 判断左右2边大小 //小的放到新数组中
				temp[num] = arr[left];
				num++;
				left++;
			} else {
				temp[num] = arr[j];
				num++;
				j++;
			}
		}
		while (left <= mid) { // 吧左边或者右边剩余的数放到数组中
			temp[num] = arr[left];
			left++;
			num++;
		}
		while (j <= right) {
			temp[num] = arr[j];
			j++;
			num++;
		}
		num = 0;
		while (i <= right) { // 吧有序数组的内容放到数组
			arr[i] = temp[num];
			i++;
			num++;
		}
		return temp;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值