I'm creating a sorting algorithm visualiser. When I click "generate", an array of unsorted integers is created and rendered to the screen. When I click the "Bubble sort" button, I want the entire array to be sorted in one go, but whats actually happening is bubble sort stops after each pass and I have to click "Bubble sort" multiple times to sort the array (see my image links for reference). I have also implemented a selection sort algorithm and I am having the same problem. How can I fix this? Any thoughts would be appreciated.
generates an array after bubble sort is clicked once
this pattern of continues until the array is sorted. I have to continuously click the "bubble sort" button to sort the array. Heres my code for the bubble sort algorithm.
//============ bubble sorts array when button is clicked
bubbleSort() {
const arr = this.state.array;
const n = arr.length;
for(let i=n-1; i>0; i--) {
for(let j=0; j<i; j++) {
setTimeout(() => { // setTimeout for each swap so we can see the swap happening
if(arr[j] > arr[j+1]) {
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
this.setState({ swaps: this.state.swaps + 1 }); // each swap increment swaps state by 1
}
this.setState({ comparisons: this.state.comparisons + 1 }) // each comparison increment comparisons state by 1
}, i * 10); // timeout is i * 10 millisecconds
}
}
this.setState({ array: arr });
}
This is my render function where I am returning JSX. render function