溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#排序算法中的歸并排序是什么

發(fā)布時(shí)間:2021-10-15 17:01:36 來源:億速云 閱讀:112 作者:柒染 欄目:編程語言

本篇文章為大家展示了C#排序算法中的歸并排序是什么,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

代碼:

//歸并排序(目標(biāo)數(shù)組,子表的起始位置,子表的終止位置)    private static void MergeSortFunction(int[] array, int first, int last)    {      try      {        if (first < last)  //子表的長度大于1,則進(jìn)入下面的遞歸處理        {          int mid = (first + last) / 2;  //子表劃分的位置          MergeSortFunction(array, first, mid);  //對劃分出來的左側(cè)子表進(jìn)行遞歸劃分          MergeSortFunction(array, mid + 1, last);  //對劃分出來的右側(cè)子表進(jìn)行遞歸劃分          MergeSortCore(array, first, mid, last); //對左右子表進(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ù)列):長度等于左右子表的長度之和。        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)      { }    }

上述內(nèi)容就是C#排序算法中的歸并排序是什么,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI