欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#排序算法之歸并排序

 更新時間:2020年01月30日 09:56:13   作者:mlovelcottage  
這篇文章主要為大家詳細介紹了C#排序算法之歸并排序,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了C#實現(xiàn)歸并排序具體代碼,供大家參考,具體內(nèi)容如下

代碼:

//歸并排序(目標數(shù)組,子表的起始位置,子表的終止位置)
  private static void MergeSortFunction(int[] array, int first, int last)
  {
   try
   {
    if (first < last) //子表的長度大于1,則進入下面的遞歸處理
    {
     int mid = (first + last) / 2; //子表劃分的位置
     MergeSortFunction(array, first, mid); //對劃分出來的左側(cè)子表進行遞歸劃分
     MergeSortFunction(array, mid + 1, last); //對劃分出來的右側(cè)子表進行遞歸劃分
     MergeSortCore(array, first, mid, last); //對左右子表進行有序的整合(歸并排序的核心部分)
    }
   }
   catch (Exception ex)
   { }
  }
 
  //歸并排序的核心部分:將兩個有序的左右子表(以mid區(qū)分),合并成一個有序的表
  private static void MergeSortCore(int[] array, int first, int mid, int last)
  {
   try
   {
    int indexA = first; //左側(cè)子表的起始位置
    int indexB = mid + 1; //右側(cè)子表的起始位置
    int[] temp = new int[last + 1]; //聲明數(shù)組(暫存左右子表的所有有序數(shù)列):長度等于左右子表的長度之和。
    int tempIndex = 0;
    while (indexA <= mid && indexB <= last) //進行左右子表的遍歷,如果其中有一個子表遍歷完,則跳出循環(huán)
    {
     if (array[indexA] <= array[indexB]) //此時左子表的數(shù) <= 右子表的數(shù)
     {
      temp[tempIndex++] = array[indexA++]; //將左子表的數(shù)放入暫存數(shù)組中,遍歷左子表下標++
     }
     else//此時左子表的數(shù) > 右子表的數(shù)
     {
      temp[tempIndex++] = array[indexB++]; //將右子表的數(shù)放入暫存數(shù)組中,遍歷右子表下標++
     }
    }
    //有一側(cè)子表遍歷完后,跳出循環(huán),將另外一側(cè)子表剩下的數(shù)一次放入暫存數(shù)組中(有序)
    while (indexA <= mid)
    {
     temp[tempIndex++] = array[indexA++];
    }
    while (indexB <= last)
    {
     temp[tempIndex++] = array[indexB++];
    }
 
    //將暫存數(shù)組中有序的數(shù)列寫入目標數(shù)組的制定位置,使進行歸并的數(shù)組段有序
    tempIndex = 0;
    for (int i = first; i <= last; i++)
    {
     array[i] = temp[tempIndex++];
    }
   }
   catch (Exception ex)
   { }
  }

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論