Search code examples
javascriptreactjssortingreact-state-management

Why doesn't sorting work correctly when I change state?


I have the BubbleSort component, but when I start the sorting process something goes wrong and my sorting works incorrect. I'm sure, the algorithm itself is written correctly. I suppose something is wrong with the setting state process, but can't figure out what it can be.

import React, {Component} from "react";
import ArrayView from "../ArrayView/ArrayView";

export default class BubbleSort extends Component{
  state = {
    elements: this.props.elements
  }

    sort = () => {
    const length = this.state.elements.length;
    for (let i = 0; i < length; i++) {
      for (let j = i + 1; j < length; j++) {
        if (this.state.elements[i].value > this.state.elements[j].value) {
          this.swap(i, j);
        }
      }
    }
  }

  swap = (first, second) => {
    this.setState((state) => {
      const newElements = [...state.elements];

      const temp = newElements[first];
      newElements[first] = newElements[second];
      newElements[second] = temp;

      return {
        elements: newElements
      }
    })
  }

  render() {
    const { elements } = this.state;

    return (
      <ArrayView elements={elements} onSort={this.sort} />
    )
  }
}

Edit sparkling-sea-dt2mg


Solution

  • The problem is that you're swapping elements in state every time and not swapping them in the array you're actually sorting in sort (the local elements array). So subsequent operations on the local elements array in sort continue to use the old values, which means the bubblesort won't work properly.

    Unless you want your component to update the DOM on every swap (which would mean substantial changes to it), change state just once, setting the new array when you're done sorting it.