DEV Community

Mi'Angel Pata
Mi'Angel Pata

Posted on

Sorting Algorithm Visualizer in Unity 3D

I created a sorting algorithm visualizer. It currently handles Insertion Sort. Not sure if I have any plans to make it do other algorithms but it would sure be fun.

I had an array of ints of size 100. I made a for loop to give values to all of the elements based off the "index+1". This would give index 0 the value of 1, index 1 the value of 2 and so forth.

Creating the Visual
Using the array's length, which is 100, I made the texture size to be 100x100. I then did a few nested for-loops that looked like this

 // Fill the whole texture with black
for (int i = 0; i < 100; i++)
        {
            for (int j = 0; j < 100; j++)
            {
                texture.SetPixel(i, j, Color.black);
            }
        }
        // Create the "bars" for our values
for (int i = 0; i < 100; i++)
        {
            for (int j = 0; j < array[i]; j++)
            {
               texture.SetPixel(i, j, Color.white);
            }
        }
Enter fullscreen mode Exit fullscreen mode

So I ended up with this:
Alt Text

I was completely satisfied. (:
But it needed to be randomized 😕

So I created a function to randomize an array and got this result:
Alt Text
Ahh, thats better (:

Drawing
I wanted it to be just like the Youtube videos that show the algorithms working step-by-step. So, with numerous phases of trial-and error (It wasn't really that bad, just sounds really cool saying it 😂) I used a Coroutine

 IEnumerator InsertionSort( int[] array)
    {
        int insertions = 0;
        for (int j = 1; j < array.Length; j++)
        {

            int key = array[j];
            int i = j - 1;
            while(i>=0 && array[i] > key)
            {
                array[i + 1] = array[i];
                i -= 1;
                this.array = array;
                yield return new WaitForSeconds(0.0002f);
                Draw(i+1,j);
                insertions++;


            }


            array[i + 1] = key;
            this.array = array;
            yield return new WaitForSeconds(0.0002f);
            Draw(i,j);
        }
}

Enter fullscreen mode Exit fullscreen mode

The Insertion Sort algorithm is pretty simple, but I wont be explaining in depth. There is a link just below this quote:

"In Insertion sort, you compare the key element with the previous elements. If the previous elements are greater than the key element, then you move the previous element to the next position."

Source : https://www.freecodecamp.org/news/sorting-algorithms-explained-with-examples-in-python-java-and-c/

When the algorithm is applied this is what we get:
Alt Text
Alt TextAlt Text

Then, once it's completely sorted from 1-100, we verify it:
Alt Text

So there we go! I hope you enjoyed this post. I will hopefully be making more, since it's kind of fun. Have a great journey ❤️

Top comments (0)