归并排序Java版

归并排序算法采用分治方法,把两个有序表合并成一个新的有序表。归并排序是一种稳定的排序算法,即相等元素的顺序不会改变。

public class MergeSort {
 private void merge(int[] a , int begin, int mid, int end, int[] temp) {
  int i = begin, j = mid + 1;
  int m = mid, n = end;
  int k = 0;
  while(i <= m && j <= n) {
   if(a[i] < a[j]) {
    temp[k++] = a[i++];
   } else {
    temp[k++] = a[j++];
   }
  }
  while(i <= m) {
   temp[k++] = a[i++];
  }
  while(j <= n) {
   temp[k++] = a[j++];
  }
  for(int h = 0; h < k; h++) {
   a[begin + h] = temp[h];
  }
 }
 
 public void mergeSort(int[] a, int begin, int end, int[] temp) {
  if(begin < end) {
   int mid = (begin + end) / 2;
   mergeSort(a, begin, mid, temp);
   mergeSort(a, mid + 1, end, temp);
   merge(a, begin, mid, end, temp);
  }
 }
 
 public static void main(String[] args) {
  int[] arrays = new int[]{7, 20, 23, 0, 4, 8, 12, 3, 18, 8};
  int[] temps = new int[arrays.length];
  MergeSort mergeSort = new MergeSort();
  mergeSort.mergeSort(arrays, 0, arrays.length - 1, temps);
 
  for(int temp : arrays) {
   System.out.print(temp + ",");
  }
 }
}

 归并排序的最好、最坏和平均时间复杂试都是O(nlogn),空间复杂度是O(n)。

猜你喜欢

转载自dujian-gu.iteye.com/blog/2238466