Sujio
Sujio

Reputation: 457

Merge sort not working as expected react state array

I'm working on a sorting visualizer, I've been debugging this for hours. I'm trying to sort an array that is stored in the state.

I've setup a codesandbox here: https://codesandbox.io/s/pensive-villani-kdh17?file=/src/SortingVisualizer/SortingVisualizer.jsx

Can someone show me where I'm going wrong?

  mergeSort = async () => {
    const { array } = this.state;
    const arry = array.slice();
    const auxArray = arry.slice();
    await this.mergeSortHelper(arry, auxArray, 0, arry.length - 1);
  };

  mergeSortHelper = async (arry, auxArray, start, end) => {
    if (start === end) {
      return;
    }
    const middle = Math.floor((start + end) / 2);
    await this.mergeSortHelper(arry, auxArray, start, middle);
    await this.mergeSortHelper(arry, auxArray, middle + 1, end);
    await this.doMerge(arry, auxArray, start, middle, end);
  };

  doMerge = async (arry, auxArray, start, middle, end) => {
    let a = start; //arry start
    let b = start; //auxArray start
    let c = middle + 1; //mid start

    while (b <= middle && c <= end) {
      if (arry[b].height <= arry[c].height) {
        arry[a] = auxArray[b];
        this.setState({ array: arry });
        await sleep(ANIMATION_SPEED_MS);
        a++;
        b++;
      } else {
        arry[a] = auxArray[c];
        this.setState({ array: arry });
        await sleep(ANIMATION_SPEED_MS);
        a++;
        c++;
      }
    }

    while (b <= middle) {
      arry[a] = auxArray[b];
      this.setState({ array: arry });
      await sleep(ANIMATION_SPEED_MS);
      a++;
      b++;
    }

    while (c <= end) {
      arry[a] = auxArray[c];
      this.setState({ array: arry });
      await sleep(ANIMATION_SPEED_MS);
      a++;
      c++;
    }
    auxArray = arry.slice();
  };

Upvotes: 2

Views: 129

Answers (2)

Sujio
Sujio

Reputation: 457

The bug was that the auxArray and arry was different after changing it and recursive calling.

Upvotes: 0

Taghi Khavari
Taghi Khavari

Reputation: 6582

I think you don't need all those complecated functions, just add these to function to your code and use them:


  increasingSort = (inputArray) => inputArray.sort((a, b) => a.height - b.height)

  decreasingSort = (inputArray) => inputArray.sort((a, b) => b.height - a.height);

check this: https://codesandbox.io/s/pedantic-architecture-vc4ox

Upvotes: 1

Related Questions