重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設、域名注冊、服務器等服務
為企業(yè)提供網(wǎng)站建設、域名注冊、服務器等服務
本篇文章為大家展示了C#排序算法中的歸并排序是什么,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
成都創(chuàng)新互聯(lián)公司是一家專業(yè)從事成都做網(wǎng)站、網(wǎng)站建設、網(wǎng)頁設計的品牌網(wǎng)絡公司。如今是成都地區(qū)具影響力的網(wǎng)站設計公司,作為專業(yè)的成都網(wǎng)站建設公司,成都創(chuàng)新互聯(lián)公司依托強大的技術實力、以及多年的網(wǎng)站運營經(jīng)驗,為您提供專業(yè)的成都網(wǎng)站建設、營銷型網(wǎng)站建設及網(wǎng)站設計開發(fā)服務!
代碼:
//歸并排序(目標數(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)容就是C#排序算法中的歸并排序是什么,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。