Merge sort issue in JavaScript code: Unable to resolve error despite debugging
P粉256487077
P粉256487077 2023-08-18 14:25:39
0
1
646
<p>I'm trying to understand all the sorting algorithms, this is the code I wrote for merge sort but it doesn't work, can you point out what's wrong in it:</p> <pre class="brush:php;toolbar:false;">solve: function (A) { let count = this.mergeSort(A); return count; }, mergeTwoSortedArrays: function (A, B) { let i = 0; let j = 0; let k = 0; let C = []; while (i < A.length && j < B.length && A[i] || B[j]) { 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; }, mergeSort: 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(c, d); }</pre> <p>Okay, the question requires me to add more details to get approval. So my approach is: split the array into two equal parts until they become an array of one element, then use a merge technique to merge the two sorted arrays. </p>
P粉256487077
P粉256487077

reply all(1)
P粉068510991

You should simply check i < A.length && j < B.length as the loop condition.

This is your updated code:

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]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template