Solution 1 :

I see no problem here, working fine at my end.

function selectionSort() {
    var arr = [1,2,4,5,6,3,10,9];
    console.log(arr);
    var n = arr.length;
    var i = 0;
    var j = 0;
    for (i = 0; i < n; ++i) {
      var min = i;
      for (j = i; j < n; ++j) {
        if (arr[min] > arr[j]) {
          min = j;
        }
      }
      var temp = arr[min];
      arr[min] = arr[i];
      arr[i] = temp;
    }
    console.log("new array", arr);
  }

Problem :

I’m trying to implement a sorting visualizer in React. I have a button which on click calls a selectionSort() function:

selectionSort() {
    var arr = this.state;
    console.log(arr);
    var n = arr.length;
    var i = 0;
    var j = 0;
    for (i = 0; i < n; ++i) {
      var min = i;
      for (j = i; j < n; ++j) {
        if (arr[min] > arr[j]) {
          min = j;
        }
      }

      var temp = arr[min];
      arr[min] = arr[i];
      arr[i] = temp;
    }
    console.log("new array", arr);
  }

However, the second console.log() is supposed to give the sorted array right? It doesn’t, and I can’t figure out what happened.

Comments

Comment posted by Vishal Pawar

you will get sorting logic on google. Just use it in your code

Comment posted by Karthik Raj

That wasn’t the problem, I just had to use

Comment posted by Hao Wu

Are you trying to mutate

Comment posted by reactjs.org/docs/…

please do

Comment posted by Karthik Raj

@HaoWu, I didn’t know that. Anyway I was just trying whether the algorithm would work. Thanks for your input, will keep it in mind!

Comment posted by messerbill

but you have got an hardcoded array here and the OP has got a react state. React states should not be set without

Comment posted by Hamza Arshad

You are right, but he was having issue getting a sorted array after the loop in console.log.

Comment posted by Karthik Raj

Just had to use

Comment posted by messerbill

@KarthikRaj read the comments under your question. this is very important

By

Leave a Reply

Your email address will not be published. Required fields are marked *