1

I am creating a sorting algorithms visualizer. I have written the following code...

    <v-select
      label="Choose Algorithm"
      append-icon="mdi-chart-bar"
      :items="sortingAlgorithmOptions"
      v-model="sortingAlgorithmChoice"
      color="secondary darken-4"
    ></v-select>

    <v-btn class="secondary darken-3 mt-3" @click="callSortingAlgorithmFunction">
      <span>Start sorting</span>
      <v-icon right>mdi-shuffle</v-icon>
    </v-btn>

    <v-card
      flat
      class="red d-inline-block mr-2"
      width="20px"
      v-for="item in arrayToSort"
      :key="item.id"
      :height="item * 10"
      ref="arrayToSort"
    ></v-card>

    data: () => ({
        sortingAlgorithmOptions: ["Merge Sort", "Quick Sort", "Bubble Sort"],
        sortingAlgorithmChoice: "Sorting",
        arrayToSort: []
      }),

    methods: {
      bubbleSort: function() {
        // Not yet implemented
        let n = this.arrayToSort.length;
        for (let i = 0; i < n; ++i) {
          for (let j = i + 1; j < n - i; ++j) {
            if (this.arrayToSort[j] < this.arrayToSort[j - 1]) {
              let temp = this.arrayToSort[j - 1];
              this.arrayToSort[j - 1] = this.arrayToSort[j];
              this.arrayToSort[j] = temp;
            }
          }
        }
      },
      callSortingAlgorithmFunction: function() {
        let event = this.sortingAlgorithmChoice;
        console.log(this.sortingAlgorithmChoice)
        if (event == "Merge Sort") {
          this.mergeSort();
        } else if (event == "Quick Sort") {
          this.quickSort();
        } else if (event == "Bubble Sort") {
          this.bubbleSort();
        }
      },

      // Called on created
      intializeRandomArray: function() {
        this.arrayToSort = [];
        for (let i = 0; i < 52; ++i) {
          this.arrayToSort.push(Math.floor(Math.random() * 55) + 10);
        }
      }
    }

But this code doesn't seem to be sorting when I click the Start sorting button.

However, if I change the selected option to some other sorting algorithm, the canvas updates with the new orientation of bars. I have put in lots of hours, gone through many revert backs and searched their docs, forums, etc., but I can not figure out what's wrong here...

1 Answer 1

1

Vue cannot detect when you directly set an item in an array with the index like this:

this.arrayToSort[j] = temp

To overcome this you need to do this:

this.$set(this.arrayToSort, j, temp)

https://stackoverflow.com/a/42808068/5671919

Read more here : https://v2.vuejs.org/v2/guide/reactivity.html#For-Arrays

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.