0

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>
        </>

    )
}

Error on running merge sort

enter image description here

enter image description here

5
  • 2
    Did you try this <button onClick={() => mergeSort(array)}>Merge Sort</button> Commented Apr 26, 2022 at 10:43
  • Yes, but getting the same error. Commented Apr 26, 2022 at 10:45
  • Use setArray(array); outside for loop and check. Also check if firstHalf and secondHalf data is of type array Commented Apr 26, 2022 at 10:48
  • Just call const sorted = mergeSort(array) after resetArray with array state and then setState(sorted) Commented Apr 26, 2022 at 11:12
  • Done!!!. firstHalf and secondHalf are type object which is array. Also passing array to onclick breaking the code. Added snippet Commented Apr 26, 2022 at 11:21

1 Answer 1

1

First, you have a problem in your algorith causing an infinite loop, here:

 while (i < firstHalf.length) sortedArray.push(firstHalf[i]);
 while (j < secondHalf.length) sortedArray.push(secondHalf[j]);

You forgot to increment i and j.

About your question, i solved it by having a mergeSort function that calls an helper function and then set the state with the sorted array. Here's the code with some comments:

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(randomIntFromInterval(5, 750));
    }
    // You can move this out of your loop
    setArray(array);
  };

  function randomIntFromInterval(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }

  // You can define a function that sort the array using merge sort
  // and then set the state
  function mergeSort() {
    const sorted = mergeSortHelper(array);
    setArray(sorted);
  }

  // This is an helper function that works correctly with recursion
  function mergeSortHelper(array) {
    if (array.length <= 1) return array;
    const middle = Math.floor(array.length / 2);
    const firstHalf = mergeSortHelper(array.slice(0, middle));
    const secondHalf = mergeSortHelper(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++]);
      }
    }

    // You forgot to increment you counters here causing an infinite loop
    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) => (
          
          //removed the styles temporarely because i couldn't read results
          <div className="array-bar" key={indx}>
            {value}
          </div>
        ))}
      </div>
      <button onClick={() => resetArray()}>Array Genrator</button>

      <button onClick={() => mergeSort()}>Merge Sort</button>
    </>
  );
}

Demo: https://stackblitz.com/edit/react-2ueaft?file=src%2FRandomArrayJanrator.js

Sign up to request clarification or add additional context in comments.

3 Comments

HEy, Thanks for the help. But It didn't work out. Getting Maximum stack limit hit at line --------const firstHalf = mergeSort(array.slice(0, middle));
did you check all the changes? that line has changed now and it call the helper function instead: const firstHalf = mergeSortHelper(array.slice(0, middle));
Ah....sorry miss that part. Thanks alot for the help!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.