Heim  >  Fragen und Antworten  >  Hauptteil

Problem bei der Zusammenführungssortierung im JavaScript-Code: Fehler konnte trotz Debugging nicht behoben werden

<p>Ich versuche alle Sortieralgorithmen zu verstehen. Dies ist der Code, den ich für die Zusammenführungssortierung geschrieben habe, aber er funktioniert nicht. Können Sie mir sagen, was darin falsch ist: </p> <pre class="brush:php;toolbar:false;">solve: function (A) { let count = this.mergeSort(A); Rückgabeanzahl; }, mergeTwoSortedArrays: Funktion (A, B) { sei i = 0; sei j = 0; sei k = 0; sei C = []; while (i < A.length && j < B.length && A[i] || B[j]) { if (A[i] < B[j]) { C[k] = A[i]; i++; k++; } anders { C[k] = B[j]; j++; k++; } } while (j < B. Länge) { C[k] = B[j]; k++; j++; } while (i < A.length) { C[k] = A[i]; k++; i++; } Rückkehr C; }, mergeSort: Funktion (a) { sei n = a.length; if (n <= 1) return a; let c = Array.from({ length: Math.floor(n / 2) }, (_, i) => a[i]); let d = Array.from({ length: n - c.length }, (_, i) => a[c.length + i]); return this.mergeTwoSortedArrays(c, d); }</pre> <p>Okay, die Frage erfordert, dass ich weitere Details hinzufüge, um eine Genehmigung zu erhalten. Mein Ansatz ist also: Teilen Sie das Array in zwei gleiche Teile auf, bis sie zu einem Array aus einem Element werden, und verwenden Sie dann eine Zusammenführungstechnik, um die beiden sortierten Arrays zusammenzuführen. </p>
P粉256487077P粉256487077398 Tage vor557

Antworte allen(1)Ich werde antworten

  • P粉068510991

    P粉0685109912023-08-19 13:00:40

    你应该简单地将 i < A.length && j < B.length 作为循环条件进行检查。

    这是你更新后的代码:

    const mergeSort = {
      solve: function (A) {
        return this.mergeSortFunction(A);
      },
      mergeTwoSortedArrays: function (A, B) {
        let i = 0;
        let j = 0;
        let k = 0;
        let C = [];
        while (i < A.length && j < B.length) {
          if (A[i] < B[j]) {
            C[k] = A[i];
            i++;
            k++;
          } else {
            C[k] = B[j];
            j++;
            k++;
          }
        }
        while (j < B.length) {
          C[k] = B[j];
          k++;
          j++;
        }
        while (i < A.length) {
          C[k] = A[i];
          k++;
          i++;
        }
        return C;
      },
      mergeSortFunction: function (a) {
        let n = a.length;
        if (n <= 1) return a;
        let c = Array.from({ length: Math.floor(n / 2) }, (_, i) => a[i]);
        let d = Array.from({ length: n - c.length }, (_, i) => a[c.length + i]);
        return this.mergeTwoSortedArrays(this.mergeSortFunction(c), this.mergeSortFunction(d));
      }
    };
    
    // 示例
    const inputArray = [38, 27, 43, 3, 9, 82, 10];
    const sortedArray = mergeSort.solve(inputArray);
    console.log(sortedArray); 
    // 输出:[3, 9, 10, 27, 38, 43, 82]

    Antwort
    0
  • StornierenAntwort