算法与数据结构_6_归并排序

  • 马上要实习面试了,总结和分析一下算法与数据结构。
    归并排序先使每个子序列有序,再使子序列段间有序。最后将两个有序表合并成一个有序表。
    时间复杂度为O(nlogn)。
public static void MergeSort
(int[]arr,int left, int right,int[]temp){
	if(left<right){
		int mid=(left+right)/2;
		//将序列不断分为子列
		MergeSort(arr,left,mid,temp);
		MergeSort(arr,mid+1,right,temp);
		//分为最小子列后开始合并
		merge(arr,left,mid,right,temp);
	}
}

public static void merge
(int[]arr,int left,int mid,int right,int[]temp){
	int l =left;//左子列起始点
	int r= mid+1;//右子列起始点
	int t=0;//temp起始点
	//合并
	while(l<=mid&&r<=right){
		if(arr[l]<arr[r]){
			temp[t]=arr[l]
			l++;
		}else{
			temp[t]=arr[r];
			r++;
		}
		t++;
	}
	//将左列和右列剩下的数加入temp
	while(l<=mid){
		temp[t]=arr[l];
		l++;
		t++;
	}
	while(r<=right){
		temp[t]=arr[r];
		r++;
		t++;
	}
	//将合并好的有序temp放回arr
	t=0;
	int tempLeft = left;//从arr的left开始放
	while(tempLeft<=right){
		arr[tempLeft]=temp[t];
		tempLeft++;
		t++;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值