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);
}
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.
you will get sorting logic on google. Just use it in your code
@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!
but you have got an hardcoded array here and the OP has got a react state. React states should not be set without
You are right, but he was having issue getting a sorted array after the loop in console.log.
@KarthikRaj read the comments under your question. this is very important