I’m sitting down to visualize the quick sort algorithm with React.js for university. After a bit of searching, I found this code for partitioning, which is also intended for React.
async function partition(arr, start, end) {
// Taking the last element as the pivot
const pivotValue = arr[end];
let pivotIndex = start;
await changeColorForPivot(end)
for (let i = start; i < end; i++) {
if (arr[i] < pivotValue) {
// Swapping elements
[arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]];
// Moving to next element
pivotIndex++;
}
}
// Putting the pivot value in the middle
[arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]]
await changeColorForPivot(pivotIndex)
return pivotIndex;
}
My array that I want to sort is in a state variable so that I can react to a change for display it visually.
const [arrForVisualisation, setArrForVisualisation] = useState([])
My question now is what exactly these two lines do in the Partition function
// Swapping elements
[arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]];
// Putting the pivot value in the middle
[arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]]
To me it seems like these two lines of code manipulate the state variable, as if they also update/change it at the same time.
To my knowledge, I always thought that you can update/change a state variable only with the corresponding setState() function.
For my further proceeding it would help me very much to understand these two lines of code, since I must still adapt the function somewhat, in order to be able to visualize the happening changes accordingly.