-2

我知道我应该处理一些输入。但是代码会是什么样子?认为

   public static void mergeSort(Comparable[] a, int left, int right) {
      if (right <= left) return;
      int mid = left + (right – left) / 2;
      mergeSort(a, left, mid);
      mergeSort(a, mid + 1, right);
      merge(a, left, mid, right);
   } 
   public void merge(Comparable[] a, int left, int mid,int right) {
     for (int k = left; k <= right; k++) aux[k] = a[k]; 
       int i = left; j = mid + 1;
     for (int k = left; k <= right; k++) {
       if (i > mid) a[k] = aux[j++];
       else if (j > right) a[k] = aux[i++];
       else if (less(aux[j], aux[i]) a[k] = aux[j++];
       else a[k] = aux[i++];
     }
  }

是归并排序方法。

4

1 回答 1

-1
public class Mergesort {
  private int[] numbers;
  private int[] helper;

  private int number;

  public void sort(int[] values) {
    this.numbers = values;
    number = values.length;
    this.helper = new int[number];
    mergesort(0, number - 1);
  }

  private void mergesort(int low, int high) {
    // Check if low is smaller then high, if not then the array is sorted
    if (low < high) {
      // Get the index of the element which is in the middle
      int middle = low + (high - low) / 2;
      // Sort the left side of the array
      mergesort(low, middle);
      // Sort the right side of the array
      mergesort(middle + 1, high);
      // Combine them both
      merge(low, middle, high);
    }
  }

  private void merge(int low, int middle, int high) {

    // Copy both parts into the helper array
    for (int i = low; i <= high; i++) {
      helper[i] = numbers[i];
    }

    int i = low;
    int j = middle + 1;
    int k = low;
    // Copy the smallest values from either the left or the right side back
    // to the original array
    while (i <= middle && j <= high) {
      if (helper[i] <= helper[j]) {
        numbers[k] = helper[i];
        i++;
      } else {
        numbers[k] = helper[j];
        j++;
      }
      k++;
    }
    // Copy the rest of the left side of the array into the target array
    while (i <= middle) {
      numbers[k] = helper[i];
      k++;
      i++;
    }

  }
} 

从这里合并排序样本

于 2013-10-01T05:39:18.443 回答