Why is my bubble sort not sorting duplicates and only firing once?

I’m building a sorting visualizer in React, but have encountered a slight error.
I’m using bubble sort to sort through a list of randomly generated numbers, the bars’ height is indicative of their number values (600 max). I want it to sort through the entire list, but it will only shift the largest item once onClick() … Not only that, but I’m having trouble when it comes to duplicate values. the duplicates are usually put right next to each other, and the cascade restarts after that point starting with the next largest value. If there were no duplicates generated, then I would only have to click sort() a bunch of times until everything shifted into the right place, so it only halfway works.

  • duplicates are resetting the sort
  • the sort() is only running once on every click
    sort() {

      const state = this.state.data;
      let i = 0
      let a = 0;
      let b = a + 1;        

      do {

        let aValue = this.state.data[a];
        let bValue = this.state.data[b];
        let aIndex = this.state.data.indexOf(aValue);
        let bIndex = this.state.data.indexOf(bValue); 

        function swap(a,b) {
          state.splice([aIndex], 1, b)
          state.splice([bIndex], 1, a)

              if(aValue > bValue && i <= state.length) { 
                swap(aValue, bValue)
        a += 1;
        b += 1;
        i += 1;
      } while (i < state.length)


38 thoughts on “Why is my bubble sort not sorting duplicates and only firing once?”

Leave a Comment