一天一算法之归并排序

<span style="font-size:18px;"><span style="white-space:pre">	</span>归并排序是3个时间复杂度为O(nlogn)唯一一个稳定的算法,不过自己没有实现出来。。。</span>
<span style="font-size:18px;"><span style="white-space:pre">	</span>还好别人的代码看懂了。。。</span>
<span style="font-size:18px;"><span style="white-space:pre">	</span>这是原文链接:<a target=_blank href="http://blog.163.com/pinbo_jiankun/blog/static/133546488201391831822169/">点击打开链接</a></span>
<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sort
{
	class MergeSorter
	{
		/// <summary>
		/// 归并排序之归:归并排序入口 
		/// Updated by Lihua at 05/06/2009
		/// </summary>
		/// <param name="data">无序数组</param>
		/// <returns>有序数组</returns>
		public static void Main (string[] args) {
			int [] arr = {3, 1, 64, 23, 34, 45, 345, 12, 3, 78, 2};
			int [] result = Sort (arr);
			foreach (int i in result) {
				Console.WriteLine (i);
			}
		}
		public static int[] Sort(int[] data) {
			//若data为null,或只剩下1 or 0个元素,返回,不排序
			if (null == data || data.Length <= 1) {
				return data;
			}
			//取数组中间下标
			int middle = data.Length >> 1;
			//初始化临时数组let,right,并定义result作为最终有序数组,若数组元素奇数个,将把多余的那元素空间预留在right临时数组
			int[] left = new int[middle];
			int[] right =  new int[data.Length - middle];
			int[] result = new int[data.Length];
			for (int i = 0; i < data.Length; i++) {
				if (i < middle) {
					left[i] = data[i];
				}
				else {
					right[i-middle] = data[i]; //此处i-middle,让我省掉定义一个j,性能有所提高
				}
			}
			left = Sort(left);//递归左数组
			right = Sort(right);//递归右数组
			result = Merge(left, right);//开始排序
			return result;
		}
		/// <summary>
		/// 归并排序之并:排序在这一步
		/// </summary>
		/// <param name="a">左数组</param>
		/// <param name="b">右数组</param>
		/// <returns>合并左右数组排序后返回</returns>
		private static int[] Merge(int[] a, int[] b) {
			//定义结果数组,用来存储最终结果
			int[] result = new int[a.Length + b.Length];
			int i = 0, j = 0, k = 0;
			while (i < a.Length && j < b.Length) {
				//左数组中元素小于右数组中元素
				if (a[i] < b[j]) {
					result[k++] = a[i++];//将小的那个放到结果数组
				}
				else {						//左数组中元素大于右数组中元素
					result[k++] = b[j++];//将小的那个放到结果数组
				}
			}
			while (i < a.Length) {			//这里其实是还有左元素,但没有右元素 
				result[k++] = a[i++];
			}
			while (j < b.Length) {			//有右元素,无左元素
				result[k++] = b[j++];
			}
			return result;//返回结果数组
		}
	}
}</span>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值