java排序算法之归并排序

排序算法之归并排序

归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)

策略(分治法将问题分(divide)成一些小的问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案"修
补"在一起,即分而治之)。
两个图,解释如何归并
先分再合:
在这里插入图片描述

package cn.ycl.dataStructures.sort;
import java.util.Arrays;
public class mergeSort {
	public static void main(String[] args) {
		int array[] = { 8, 4, 5, 7, 1, 3, 6, 2 };
		int temp[] = new int[array.length]; // 归并排序需要一个额外空间
		merges(array, 0, array.length - 1, temp);
		System.out.println(Arrays.toString(array));
	}
//分+合的方法
	public static void merges(int array[], int left, int right, int temp[]) {
		if (left < right) {
			int mid = (left + right) / 2;
			// 中间索引
			// 向左递归进行分解
			merges(array, left, mid, temp);
			// 向右递归进行分解
			merges(array, mid + 1, right, temp);
			// 合并
			merge(array, left, mid, right, temp);
		}
	}
	// 合并方法
	// array,排序数组;left,左边有序序列的初始索引;right,右边有序序列的初始索引;mid,中间索引;temp,做中转的数组
	public static void merge(int array[], int left, int mid, int right, int temp[]) {
		int i = left;
		int j = mid + 1;
		int t = 0;// t表示temp中转数组的初始索引
		// 第一步:先把左右两边有序的数据按照规则填充到temp数组,直到有一边处理完毕为止
		while (i <= mid && j <= right) {
			if (array[i] < array[j]) {
				temp[t] = array[i];
				i += 1;
				t += 1;
			} else {
				temp[t] = array[j];
				j += 1;
				t += 1;
			}
		}
		// 第二步:把剩余数据的一边的数据依次全部填充到temp
		while (i <= mid) {
			temp[t] = array[i];
			i += 1;
			t += 1;
		}
		while (j <= right) {
			temp[t] = array[j];
			j += 1;
			t += 1;
		}
		// 第三步:将temp数组的元素拷贝到array
		// 将 temp 数组的元素拷贝到 arr
		// 注意,并不是每次都拷贝所有 t = 0; int tempLeft = left; //
		// 第一次合并 tempLeft = 0 , right = 1 // tempLeft = 2 right = 3 // tL=0 ri=3 //最后一次
		// tempLeft = 0 right = 7
		t = 0;
		int tempLeft = left;
		while (tempLeft <= right) {
			array[tempLeft] = temp[t];
			t += 1;
			tempLeft += 1;
		}
	}
}

我是“道祖且长”,一个在互联网苟且偷生的Java程序员

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

三七有脾气

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

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

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

打赏作者

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

抵扣说明:

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

余额充值