이 재귀가 기본 사례를 얻지 못하는 이유는 무엇입니까? (Why is this Recursion not getting its base case?)


문제 설명

이 재귀가 기본 사례를 얻지 못하는 이유는 무엇입니까? (Why is this Recursion not getting its base case?)

병합 정렬 기능을 구현하려고 합니다. 내 코드는 다음과 같습니다.

void
merge_sort(int a[], int l, int u)
{
  int mid = (l + u) / 2;
  if (mid) {
    merge_sort(a, l, mid);
    merge_sort(a, mid + 1, u);
    merge(a, l, mid, u);
  }
}

mid 값이 0인 것을 확인했지만 다시 초기 값을 가져오고 무한 루프로 바뀝니다.

피>

참조 솔루션

방법 1:

What you are supposed to check is

if (mid != l) {
    // ...
}

See a complete merge sort implementation here.

Edit This assumes u is not in the range of elements that are meant to be sorted. If it is, you should testif (l < u).

방법 2:

You must check if the range has at least 2 elements:

/* sort a range of elements from `l` to `u` inclusively */
void merge_sort(int a[], int l, int u) {
    if (l < u) {
        int mid = l + (u ‑ l) / 2;
        merge_sort(a, l, mid);
        merge_sort(a, mid + 1, u);
        merge(a, l, mid, u);
    }
}

If the upper bound u is not included in the range, the code should be changed to:

/* sort a range of elements from `l` included to `u` excluded */
void merge_sort(int a[], int l, int u) {
    if (u ‑ l >= 2) {
        int mid = l + (u ‑ l) / 2;
        merge_sort(a, l, mid);
        merge_sort(a, mid, u);
        merge(a, l, mid, u);
    }
}

(by NastikAyxan Haqverdilichqrlie)

참조 문서

  1. Why is this Recursion not getting its base case? (CC BY‑SA 2.5/3.0/4.0)

#mergesort #C++ #recursion






관련 질문

파이썬에 대한 병합 정렬(잘못된 것을 찾을 수 없음) (Merge Sort in place for python (Cant find what is wrong))

두 가지 빠른 수정 문제 - 병합 정렬 (two quick fix issues - Merge Sort)

Java로 작성된 병합 정렬 프로그램이 작동하지 않습니까? (My merge sort program written in Java is not working?)

MergeSort 문제: "... VariableDeclaratorId"가 FormalParameterList를 완료합니다. (MergeSort Issues: "... VariableDeclaratorId" to complete FormalParameterList)

크기가 16인 배열로 병합 정렬의 복잡성을 찾는 방법 (how can we find the complexity of merge sort with an array of size 16)

Java 병합 정렬의 정렬 부분 이해 (Understanding the sort part of Java Merge sort)

이 재귀가 기본 사례를 얻지 못하는 이유는 무엇입니까? (Why is this Recursion not getting its base case?)

Java 오류: java.lang.IllegalArgumentException: 비교 방법이 일반 계약을 위반함 (Java Error: java.lang.IllegalArgumentException: Comparison method violates its general contract)

수정된 MergeSort 런타임 (Modified MergeSort runtime)

내 병합 정렬 프로그램이 Java에서 범위를 벗어난 배열을 보여줍니다. (My merge sort program shows an array out of bound in Java)

Array Merge sort Sorting Count and Sorting time Python (Array Merge sort Sorting Count and Sorting time Python)

병합 정렬을 사용하여 연결 목록 정렬에 대한 오답 얻기 (Getting wrong answer for sorting linked list using merge sort)







코멘트