归并排序

本文介绍了一种高效的排序算法——归并排序。通过递归将数组分成较小的部分进行排序,然后合并这些已排序的部分来实现整体排序。文章详细展示了归并排序的实现过程,并提供了完整的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当一个需要排序的数组前后两部分为排好序的时候,我们就会用到归并排序,即把前后两个数组合为一个排好序的数组,如果不是前后两部分排好序的,则用分治法使其前后两部分排好序,代码如下:

/*
 * merge sort
 * @Author: lvlang1993
 * */
public class MergeSort {
	public static void main(String[] args) {
		int arr[] = {6, 1, 4, 3, 8, 5, 48, 10};;

		mergeSort(arr, 0, arr.length - 1);
		System.out.println("mergeSort test");
		for(int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
	}
    
    /*
	 * merge sort by making recurisive calls
	 * @Param: arr, the array to be sorted
	 * @Param: lt, the left begin index
	 * @Param: rt, the right end index
	 * @Return
	 * */
	public static void mergeSort(int arr[], int lt, int rt) {
		if(lt == rt) {
			return ;
		}
		else {
			int mid = (lt + rt) / 2;
			mergeSort(arr, lt, mid);//merge sort the left subarray
			mergeSort(arr, mid + 1, rt);//merge sort the right subarray
			merge(arr, lt, mid + 1, rt);//merge the array after the left and right subarray sorted
		}
	}
    
    /*
	 * merge two sorted halves of a subarray
	 * @Param: arr, the array to be sorted
	 * @Param: beginIndex, the begin index
	 * @Param: middleIndex, the middle index
	 * @Param: endIndex, the end index
	 * @Return
	 * */
	public static void merge(int arr[], int beginIndex, int middleIndex, int endIndex) {
		//split arr into arrLeft and arrRight
		int arrLeftSize = middleIndex - beginIndex;
		int arrRightSize = endIndex - middleIndex + 1;
		int arrLeft[] = new int[arrLeftSize];
		int arrRight[] = new int[arrRightSize];

		for(int i = beginIndex; i < middleIndex; i++) {
			arrLeft[i - beginIndex] = arr[i];
		}
		for(int i = middleIndex; i <= endIndex; i++) {
			arrRight[i - middleIndex] = arr[i];
		}
        
        //compare the arrLeft and arrRight val, then put the min one into the arr
		int x = 0, y = 0, z = beginIndex;//two subarrays index and the arr index
		while(x < arrLeftSize && y < arrRightSize) {//under the size
			if(arrLeft[x] < arrRight[y]) {
				arr[z] = arrLeft[x];
				x++;
				z++;
			}
			else {
				arr[z] = arrRight[y];
				y++;
				z++;
			}
		}

        //after the arrRight all in the arr but arrLeft isn't
		while(x < arrLeftSize) {
			arr[z] = arrLeft[x];
			x++;
			z++;
		}

        //after the arrLeft all in the arr but arrRight isn't
		while(y < arrRightSize) {
			arr[z] = arrRight[y];
			y++;
			z++;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值