java實現歸併排序演算法_java

來源:互聯網
上載者:User

歸併排序演算法思想:
分而治之(divide - conquer);每個遞迴過程涉及三個步驟
第一, 分解: 把待排序的 n 個元素的序列分解成兩個子序列, 每個子序列包括 n/2 個元素.
第二, 治理: 對每個子序列分別調用歸併排序MergeSort, 進行遞迴操作
第三, 合并: 合并兩個排好序的子序列,產生排序結果.

public static void mergeSort(int[] a, int[] tmp, int left, int right) {    if (left < right) {      int mid = left + (right - left) / 2;      mergeSort(a, tmp, left, mid);// 左排序      mergeSort(a, tmp, mid + 1, right);// 右排序      merge(a, tmp, left, mid + 1, right);// 左右合并    }  }public static void merge(int[] a, int[] tmp, int left, int rightPos,      int right) {    int leftEnd = rightPos - 1;    int tmpPos = left;    int num = right - left + 1;    while (left <= leftEnd && rightPos <= right) {      if (a[left] < a[rightPos]) {        tmp[tmpPos++] = a[left++];      } else {        tmp[tmpPos++] = a[rightPos++];      }    }    while (left <= leftEnd) {      tmp[tmpPos++] = a[left++];    }    while (rightPos <= right) {      tmp[tmpPos++] = a[rightPos++];    }    for (int i = 0; i < num; i++, right--) {      a[right] = tmp[right];    }  }

歸併演算法示意圖:

以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.