java [MergeSort] Merge Sort #LeetCode #Java #Recursion #Sort

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java [MergeSort] Merge Sort #LeetCode #Java #Recursion #Sort相关的知识,希望对你有一定的参考价值。

public class Solution {
  public int[] mergeSort(int[] array) {
    // Write your solution here
    if (array == null || array.length == 0) {
    	return array;
    }	
    int[] helper = new int[array.length];
    mergeSort(array, helper, 0, array.length - 1);
    return array;
  }
  
  private void mergeSort(int[] array, int[] helper, int left, int right) {
  	if (left >= right) {
      	return;
    }
    int mid = left + (right - left) / 2;
    
    mergeSort(array, helper,  left, mid);
    mergeSort(array, helper, mid + 1, right);
	combine(array, helper, left, mid, right);
    
  }
  
  private void combine(int[] array, int[] helper, int left, int mid, int right) {
  	for (int i = left; i <= right; i++) {
      helper[i] = array[i];
    }
    
    int leftIndex = left;
    int rightIndex = mid + 1;
    
    while (leftIndex <= mid && rightIndex <= right) {
      if (helper[leftIndex] <= helper[rightIndex]) {
      	array[left++] = helper[leftIndex++];
      } else {
      	array[left++] = helper[rightIndex++];
      }
      
    }
    
    while (leftIndex <= mid) {
    	array[left++] = helper[leftIndex++];
    }
  }
}

以上是关于java [MergeSort] Merge Sort #LeetCode #Java #Recursion #Sort的主要内容,如果未能解决你的问题,请参考以下文章

为啥在 MergeSort 中使用 InsertionSort 而不是 Merge 平均更快?

mergeSort算法的Python实现

merge sort

python代码实现归并排序(Merge Sort )

Educational Codeforces Round 30 D. Merge Sort

归并排序 MergeSort