Open In App

Selection Sort Visualizer in JavaScript

Last Updated : 17 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Selection sort is the simplest sorting algorithm that works by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. 

In order to know more about it. Please refer to Selection Sort

An algorithm like Selection Sort can be easily understood by visualizing instead of long codes. In this article, Selection Sort Visualizer is implemented using HTML, CSS & JavaScript.

Pre-requisites:

Approach

  • Button Generate New Array generates an array of random values usingthe Math.random() function and a bar corresponding to that value in terms of height.
  • Different colors are used to indicate which elements are unsorted(sky-blue), compared(darkblue & red) & sorted(lightgreen).
  • Button Selection Sort the elements using the selection sort algorithm.
  • Finally, elements are sorted.

Example: Click Generate New Array button to generate a new random array. Click the Selection Sort button to perform Visualization.

HTML
<!DOCTYPE html>
<html lang="en">

<!-- head -->

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <!-- title -->
    <title>Sorting Visualizer</title>

    <!-- linking style.css -->
    <link href="style.css" rel="stylesheet" />
</head>

<!-- body -->

<body>
    <section class="head">Selection Sort Visualizer</section>
    <section class="data-container"></section>

    <!-- "Generate New Array" button -->
    <button class="btn1" onclick="generate()" id="Button1">
        Generate New Array</button>

    <!-- "Selection Sort" button -->
    <button class="btn2" 
            onclick="SelectionSort(),disable()" id="Button2">
        Selection Sort</button>
</body>

<!-- linking index.js -->
<script src="index.js"></script>

</html>
CSS JavaScript

Output:

  • New array generated:
  • After the sorting:


Next Article

Similar Reads

three90RightbarBannerImg