Open In App

p5.js | Quick Sort

Last Updated : 09 Jul, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.

  • Always pick first element as pivot.
  • Always pick last element as pivot.
  • Pick a random element as pivot.
  • Pick median as pivot.

Approach:

  • Firstly take an array of random values.
  • Draw rectangle side-by-side according to the values at that array’s index.
  • Implement QuickSort Algorithm in p5.js.
  • Assign time delays in order to visualise the changes made at each successive stage.

Example:




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="UTF-8">
      
    <title>QuickSort Sorting Algorithm</title>
      
    <script src=
    type="text/javascript"></script>
      
    <style
        body {
            padding: 0;
            margin: 0;
        
        canvas {
            vertical-align: top;
        
    </style>
</head>
  
<body>
    <script type="text/javascript">
          
        // Assign Global Values
        let values = [];
        let w = 20;
        let states = [];
        function setup() {
          
            // Create Canvas of given Size
            createCanvas(800, 500);
          
            // Assign Array of Random Values
            values = new Array(floor(width/w));
              
            for(let i = 0; i < values.length; i++) {
                values[i] = float(random(height));
                states[i] = -1; 
            }
              
            // To print values to Browser's Console
            print("Unsorted Array:" + values);
              
            // Invoke QuickSort Function
            quickSort(values, 0, values.length);
              
            print("Sorted Array:" + values);
        }
          
        // Asynchronous Definition of Quick Sort Function
        async function quickSort(arr, start, end) {
            if(start >= end) {
                return;
            }
            let index = await partition(arr, start, end);
            states[index] = -1;
              
            // Promise.all is used so that each function
            // should invoke simultaneously
            await Promise.all([quickSort(arr, start, index-1),
                    quickSort(arr, index+1, end)]);
        }
          
        // Asynchronous Definition of Partition Function
        async function partition(arr, start, end) {
              
            for(let i = start; i< end; i++) {
                states[i] = 1;
            }
              
            let pivotIndex = start;
            let pivotValue = arr[end];
            states[pivotIndex] = 0;
              
            for(let i = start; i < end; i++) {
                if(arr[i]<pivotValue) {
                    await swap(arr, i, pivotIndex);
                    states[pivotIndex] = -1;
                    pivotIndex++;
                    states[pivotIndex] = 0;
                }
            }
              
            await swap(arr, pivotIndex, end);
              
                for(let i = start; i < end; i++) {
                    states[i] = -1;
                }
              
            return pivotIndex;
        }
          
        // Definition of Draw function
        function draw() {
              
            // Set Background Color 
            background(51);
              
            for(let i = 0; i < values.length; i++) {
                stroke(0);
                fill(255);
                  
                if(states[i] == 0) {
                  
                    // Pivot Element
                    fill(255, 0, 0);
                }
                else if (states[i]==1) {
                    // Sorting bar
                    fill("#58FA82");
                }
                else {
                    // Sorted Bars
                    fill(255);
                }
                  
                rect(i*w, height - values[i], w, values[i]);
            }
        }
          
        async function swap(arr, a, b) {
              
            // Call to sleep function
            await sleep(100);
            let t = arr[a];
            arr[a] = arr[b];
            arr[b] = t;
        }
          
        // Definition of sleep function
        function sleep(ms) {
            return new Promise(resolve
                    => setTimeout(resolve, ms));
        }
    </script>
</body>
  
</html>                    


Output:



Previous Article
Next Article

Similar Reads

Quick Sort vs Merge Sort
Quick sort is an internal algorithm which is based on divide and conquer strategy. In this: The array of elements is divided into parts repeatedly until it is not possible to divide it further.It is also known as “partition exchange sort”.It uses a key element (pivot) for partitioning the elements.One left partition contains all those elements that
4 min read
Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
Why is Quick Sort preferred for arrays? Below are recursive and iterative implementations of Quick Sort and Merge Sort for arrays. Recursive Quick Sort for array. Iterative Quick Sort for arrays. Recursive Merge Sort for arrays Iterative Merge Sort for arrays Quick Sort in its general form is an in-place sort (i.e. it doesn't require any extra stor
5 min read
Bucket Sort vs Quick Sort
Bucket Sort and Quick Sort are two different sorting algorithms, each with its own characteristics, advantages, and disadvantages. In this article, we will provide a detailed overview of all the differences between Bucket Sort and Quick Sort. Bucket Sort:Bucket Sort is a non-comparison sorting algorithm that divides the input array into a number of
3 min read
Advanced Quick Sort (Hybrid Algorithm)
Prerequisites: Insertion Sort, Quick Sort, Selection SortIn this article, a Hybrid algorithm with the combination of quick sort and insertion sort is implemented. As the name suggests, the Hybrid algorithm combines more than one algorithm. Why Hybrid algorithm: Quicksort algorithm is efficient if the size of the input is very large. But, insertion
9 min read
Visualization of Quick sort using Matplotlib
Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the array, Approach : We will generate an array with random elements.The algorithm will be called on that arr
3 min read
3D Visualisation of Quick Sort using Matplotlib in Python
Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use Matplotlib to plot bar graphs and animate them to represent the elements of the array. Let's see the 3D Visualizations of
3 min read
Improvement on the Quick Sort Algorithm
Prerequisite: QuickSort Algorithm The quicksort algorithm discussed in this article can take O(N2) time in the worst case. Hence, certain variations are needed which can efficiently partition the array and rearrange the elements around the pivot. Single Pivot Partitioning: In single pivot partitioning the array A[] can be divided into {A[p], A[p +
6 min read
Quick Sort(Hoare's Partition) Visualization using JavaScript
[video width="786" height="514" mp4="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210225121659/hoare.mp4"][/video]GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned into two parts and how we get the fina
4 min read
Quick Sort(Lomuto Partition) Visualization using JavaScript
GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned using Lomuto Partition and then how we get the final sorted array. We will also visualize the time complexity of Quick Sort. Reference: Quick SortLomuto Partitio
4 min read
Is Quick Sort Algorithm Adaptive or not
Pre-Requisites: Quick Sort Algorithm Adaptiveness in the Quick Sort Algorithm refers to the decision that if we are given an array that is already sorted, then the operations should be Performed or Not, i.e., if the number of operations performed on sorted Array is Not Equal to the operations performed on unsorted Array, then the Algorithm is known
8 min read