合并排序实现shuffles数组但不排序

时间:2014-01-31 07:13:06

标签: java sorting merge divide-and-conquer

我是初学程序员。这是我在Java中使用MergeSort算法的实现。 我似乎无法解决这个问题。

数组被洗牌但没有被排序。有人可以指出我的错吗?

public static int[] divide(int a[], int n, int low, int high) {
  if (low == high) {
    int[] b = { a[low] };
    return b;
  }
  int mid = (low + high) / 2;

  divide(a, n / 2, low, mid);
  divide(a, n / 2, mid + 1, high);
  return conquer(a, low, mid, high);
}

public static int[] conquer(int a[], int low, int mid, int high) {
  int p = low;
  int q = mid + 1;
  int[] sorted = new int[high - low + 1];
  int current = 0;
  while (p <= mid && q <= high) {
    if (a[p] < a[q]) {
      sorted[current++] = a[p++];
    } else
      sorted[current++] = a[q++];
  }
  if (p <= mid) {
    while (p <= mid) {
      sorted[current++] = a[p++];
    }
  }
  if (q <= high) {
    while (q <= high) {
      sorted[current++] = a[q++];
    }
  }

  return sorted;
}

1 个答案:

答案 0 :(得分:0)

主要问题是你调用divide而不是使用返回值(已排序的子数组)。 由于你没有使用中期结果,当你打电话征服时,它并不是真正的“征服”。

可以修改如下:

public static int[] divide(int a[], int low, int high) {
    if (low == high) {
        int[] b = { a[low] };
        return b;
    }
    int mid = (low + high) / 2;

    int[] lower = divide(a, low, mid);
    int[] higher = divide(a, mid + 1, high);
    return conquer(lower, higher);
}

public static int[] conquer(int[] low, int[] high) {
    int p = 0;
    int q = 0;
    int[] sorted = new int[high.length + low.length];
    int current = 0;
    while (p < low.length && q < high.length) {
        if (low[p] <= high[q]) {
            sorted[current++] = low[p++];
        } else
            sorted[current++] = high[q++];
    }
    while (p <= low.length-1) {
        sorted[current++] = low[p++];
    }
    while (q <= high.length-1) {
        sorted[current++] = high[q++];
    }
    return sorted;
}

使用代码:

int[] a = {3,1,2};
a = divide(a, 0, 2);
System.out.println(Arrays.toString(a));

打印:

[1, 2, 3]