一天一算法之归并排序
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>
相关文章推荐
- win7 批处理获取本地网关
- 使用DDMS测试安卓手机APP的性能(android)
- 第 三 十 六 天:二 阶 段 复 习(七)
- error:关于const变量来初始化数组
- Matlab与C++的混合编程
- Android持续集成--JENKINS+GRADLE+JACOCO+SONARQUBE(四)
- 分水岭超像素
- UVA 3882【dp】【简单数学】
- express
- java编程思想-多态
- QFIL
- 愿望思维
- JAVA设计模式(11) —<结构型>组合模式(Composite)
- 学习maven的使用,看到一篇很实用的入门教程(菜鸟级入门)
- 百度地图JavaScript API自定义覆盖物、自定义信息窗口增删时的显示问题
- 学习笔记03-java常用类
- uboot移植与OS移植
- iOS -实现UIView圆角显示的方法
- Android文字局部变色 TextView文字部分变色代码
- Zookeeper学习7_Zookeeper节点的增加及故障演练