B
B
BitNeBolt2021-04-24 15:20:18
Java
BitNeBolt, 2021-04-24 15:20:18

Why does merge sort take so long?

Why is an array of 30 numbers sorted in about a second and a half? What is the implementation error?

public static void mergeSort(int[] a) {
    int[] temp = new int[a.length];
    mergeSort(a, temp, 0, a.length-1);
  }

  private static void mergeSort(int[] a, int[] temp, int lo, int hi) {
    if (lo >= hi) return;

    /*if ((hi - lo) < 32) {
      insertionSort(a, lo, hi);
      return;
    }*/

    int mid = (lo + hi) / 2;

    mergeSort(a, temp, 0, mid);
    mergeSort(a, temp, mid+1, hi);

    merge(a, temp, lo, hi);
  }

  private static void merge(int[] a, int[] temp, int lo, int hi) {
    int mid = (lo + hi) / 2;

    int left = 0;
    int right = mid + 1;

    for (int i = 0; i < a.length; i++) temp[i] = a[i];

    for (int i = 0; i < a.length; i++) {
      if (left <= mid && right < a.length) {
        if (temp[left] < temp[right]) {
          a[i] = temp[left++];
        } else {
          a[i] = temp[right++];
        }
      } else if (left <= mid) {
        a[i] = temp[left++];
      } else if (right < a.length) {
        a[i] = temp[right++];
      }
    }
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-04-24
@BitNeBolt


mergeSort(a, temp, 0, mid);

It is necessary to sort the part from lo to mid. Not from 0.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question