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

C#排序算法之歸并排序

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

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

代碼:

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論