您的位置:首页 > 其它

一天一算法之归并排序

2015-10-20 18:58 288 查看
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: