So, I've been working on a project. I want to pass the value of the state to the functions as a parameter or maybe my understanding is wrong. I created a function called resetArray. Where I'm creating the array of random values and setting the state of the array. Now I want that array to pass as a parameter to the mergeSort function to sort the array but I don't think my approach is correct.
import React from 'react'
import { useEffect } from 'react';
import { useState } from 'react'
import './Randomarray.css'
export default function RandomArrayJanrator() {
const [array, setArray] = useState([]);
useEffect(() => {
resetArray();
}, [])
const resetArray = () => {
const array = [];
for (let i = 0; i < 310; i++) {
//array.push(Math.abs(Math.floor(Math.random() * (1000 - 10) - 10)));
array.push(randomIntFromInterval(5, 750));
setArray(array);
}
}
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function mergeSort(array) //trying to pass state here as a perameter
{
if (array.length === 1) return array;
const middle = Math.floor(array.length / 2);
const firstHalf = mergeSort(array.slice(0, middle));
const secondHalf = mergeSort(array.slice(middle));
const sortedArray = [];
let i = 0, j = 0;
while (i < firstHalf.length && j < secondHalf.length) {
if (firstHalf[i] < secondHalf[j]) {
sortedArray.push(firstHalf[i++])
}
else {
sortedArray.push(secondHalf[j++]);
}
}
while (i < firstHalf.length) sortedArray.push(firstHalf[i]);
while (j < secondHalf.length) sortedArray.push(secondHalf[j]);
return sortedArray;
}
return (
<>
<div className='container'>
{array.map((value, indx) => (
<div className='array-bar' key={indx} style={{ height: `${value}px`, color: '#fff', fontSize: '2px' }}>{value}</div>
))}
</div>
<button onClick={() => resetArray()}>Array Genrator</button>
<button onClick={() => mergeSort()}>Merge Sort</button>
</>
)
}



<button onClick={() => mergeSort(array)}>Merge Sort</button>setArray(array);outsideforloop and check. Also check iffirstHalfandsecondHalfdata is of type arrayconst sorted = mergeSort(array)afterresetArraywitharraystate and thensetState(sorted)