C#排序算法之归并排序

发布时间:2020-09-08 20:04:13 作者:mlovelcottage
来源:脚本之家 阅读:151

本文实例为大家分享了C#实现归并排序具体代码,供大家参考,具体内容如下

代码:

//归并排序(目标数组,子表的起始位置,子表的终止位置)
  private static void MergeSortFunction(int[] array, int first, int last)
  {
   try
   {
    if (first < last) //子表的长度大于1,则进入下面的递归处理
    {
     int mid = (first + last) / 2; //子表划分的位置
     MergeSortFunction(array, first, mid); //对划分出来的左侧子表进行递归划分
     MergeSortFunction(array, mid + 1, last); //对划分出来的右侧子表进行递归划分
     MergeSortCore(array, first, mid, last); //对左右子表进行有序的整合(归并排序的核心部分)
    }
   }
   catch (Exception ex)
   { }
  }
 
  //归并排序的核心部分:将两个有序的左右子表(以mid区分),合并成一个有序的表
  private static void MergeSortCore(int[] array, int first, int mid, int last)
  {
   try
   {
    int indexA = first; //左侧子表的起始位置
    int indexB = mid + 1; //右侧子表的起始位置
    int[] temp = new int[last + 1]; //声明数组(暂存左右子表的所有有序数列):长度等于左右子表的长度之和。
    int tempIndex = 0;
    while (indexA <= mid && indexB <= last) //进行左右子表的遍历,如果其中有一个子表遍历完,则跳出循环
    {
     if (array[indexA] <= array[indexB]) //此时左子表的数 <= 右子表的数
     {
      temp[tempIndex++] = array[indexA++]; //将左子表的数放入暂存数组中,遍历左子表下标++
     }
     else//此时左子表的数 > 右子表的数
     {
      temp[tempIndex++] = array[indexB++]; //将右子表的数放入暂存数组中,遍历右子表下标++
     }
    }
    //有一侧子表遍历完后,跳出循环,将另外一侧子表剩下的数一次放入暂存数组中(有序)
    while (indexA <= mid)
    {
     temp[tempIndex++] = array[indexA++];
    }
    while (indexB <= last)
    {
     temp[tempIndex++] = array[indexB++];
    }
 
    //将暂存数组中有序的数列写入目标数组的制定位置,使进行归并的数组段有序
    tempIndex = 0;
    for (int i = first; i <= last; i++)
    {
     array[i] = temp[tempIndex++];
    }
   }
   catch (Exception ex)
   { }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. C++归并排序算法的代码
  2. php排序算法—归并排序的案例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

归并排序

上一篇:Java8如何将Array转换为Stream的实现代码

下一篇:Python实现查找数组中任意第k大的数字算法示例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》