如何测试合并排序是否稳定?

时间:2013-10-01 05:17:38

标签: java sorting

我知道我应该投入一些工作。但代码会是什么样的?假设

   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++];
     }
  }

是mergesort方法。

1 个答案:

答案 0 :(得分:-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++;
    }

  }
} 

合并来自here

的排序示例