Experience the quick sort programming algorithm in action using Vue.js without the hassle of dealing with Promises

I am currently experimenting with the quicksort algorithm visualization using Vue.js for self-educational purposes. However, I am facing some difficulties with async/await implementation. Although array filling and shuffling seem to work fine (although I am not sure if it's implemented correctly), the sorting behavior is quite odd. I suspect that this has something to do with the async/await in the recursion process. As I am not a professional programmer and only have basic knowledge, any assistance would be greatly appreciated. And yes, I'm aware that the code snippet may look messy :)

// noprotect

var app = new Vue({
  el: '#app',
  data: {
    numArray: []
  },
  methods: {
    fillArray: function(event) {
      for (var i = 0; i<30; i++) {
        this.numArray.push(i);
      }
    },
    shuffleArray: function(event) {
      var tempArray = myShuffleFunction(this.numArray);
      this.numArray = tempArray;
    },
    sortArray: function(event) {
      this.numArray = implementQuickSort(this.numArray,0,this.numArray.length-1)
      console.log(this.numArray);
    }
  }
})
Vue.config.devtools = false;

function sleep(ms = 0) {
  return new Promise(r => setTimeout(r, ms));
};

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

function myShuffleFunction(array) {
  var len = array.length,
      tempValue, randomIndex;

  
  while (0 !== len){
    
   
    randomIndex = Math.floor(Math.random() * len);
    len -= 1;

    // Swap elements.
    tempValue = array[len];
    Vue.set(array,len,array[randomIndex]);
    Vue.set(array,randomIndex,tempValue);
  }

  return array;
}


function implementQuickSort(arr, left, right) {
  var len = arr.length,
      p,
      partIndex;


  if (left < right) {
    p = right;
    partIndex = partition(arr, p, left, right);

    implementQuickSort(arr, left, partIndex - 1);
    implementQuickSort(arr, partIndex + 1, right);
  }
  return arr;
}
//async function partition(arr, pivot, left, right) {
function partition(arr, pivot, left, right) {
  var pivotValue = arr[pivot],
      partIndex = left;

  for (var i = left; i < right; i++) {
    if (arr[i] < pivotValue) {
      exchange(arr, i, partIndex);
      await sleep(100);
      partIndex++;
    }
  }
  exchange(arr, right, partIndex);
  await sleep(100);
  return partIndex;
}

function exchange(arr, i, j) {
  var valueTemp = arr[i];
  
  Vue.set(arr,i,arr[j]);
  Vue.set(arr,j,valueTemp);
}
body {
  font-family: sans-serif;
  font-size: 12px;
  font-weight: 700;
}

.container {
  display: block;
  clear: both;
  overflow: hidden;
}

.el {
  border: 1px solid lightgray;
  float: left;
  width: 2%;
  text-align: center;
  padding: 10px 0;
  width: 25px;
  margin: 0 2px;
}


.btn {
  display: block;
  margin-top: 20px;
  clear: both;
  border: 2px solid orange;
  text-align: center;
  padding-top: 10px;
  padding-bottom: 10px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="app">
    <div class="container" id="scene1">
      <div class="el" v-for="item in numArray">{{ item }}</div>
    </div>
    <a href="#" v-on:click.prevent="fillArray" class="btn">Fill array</a>
    <a href="#" v-on:click.prevent="shuffleArray" class="btn">Shuffle array</a>
    <a href="#" v-on:click.prevent="sortArray" class="btn">Sort array</a>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

Answer №1

The async function named partition does not return an integer, but rather a promise. To properly handle this asynchronous behavior, the quicksort function must also be made asynchronous.

async function quickSort(arr, left, right) {
  const len = arr.length;

  if (left < right) {
    const pivot = right;
    const partitionIndex = await partition(arr, pivot, left, right);

    await quickSort(arr, left, partitionIndex - 1);
    await quickSort(arr, partitionIndex + 1, right);
  }
  return arr;
}

This same logic applies to the app's method called sortArray.

Answer №2

Yes, this method worked perfectly for me!

function customSortAlgorithm(arr) {
return new Promise(async (resolve, reject) =>{
if (arr.length < 2) resolve(arr)
else {
let [pivot, ...arr1] = arr;
let right = [], left = []
for (let i of arr1) {
if (i < pivot) left.push(i)
else right.push(i)
}
let sortedArr = await Promise.all([customSortAlgorithm(left),customSortAlgorithm(right)])
// console.log(`pivot: ${pivot}, sortArr: ${sortedArr}`)
resolve([...sortedArr[0], pivot, ...sortedArr[1]])
}
})
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

Adjust the image size without losing sharpness

I'm currently working on a web application for Minecraft and I am looking for a way to resize someone's skin without losing quality. I believe javascript might be the solution to this issue. ...

What is the reason behind not being able to assign identical names to my SailsJS models and MySQL tables?

Recently diving into Sails JS, I found myself in unfamiliar territory with RESTful APIs. Following the guide, I created a User model to correspond with my existing users table. Adding attributes based on the table's columns was straightforward, and a ...

How can I transfer a selected value from a unique dropdown component to react-hook-form?

I am utilizing react-hook-form for form validation in this Gatsby project. However, my dropdown component is not a <select> tag but a customized component created with divs and an unordered list. This design choice was made to meet our specific custo ...

Display a JavaScript dialogue box containing a PHP variable

Is there a way to display the correct JavaScript box when using a While loop in PHP? Here is the code snippet: while($result= mysql_fetch_array($data)){ <tr class="<?php echo $style;?>"> <td><?php echo $result['commis ...

Display 'Div 1' and hide 'Div 2' when clicked, then reveal 'Div 2' and hide 'Div 1' when a different button is clicked

I need help figuring out how to make two separate buttons work. One button should display 'Div 1' and hide 'Div 2', while the other button should show 'Div 2' and hide 'Div 1' when clicked. My knowledge of jquery an ...

Is it possible for the relative path of a gif image to become invalid when added to a div?

Question Context: In the view, I have a form that will show a loading 'spinner' gif when a user submits it. The Problem: If I place the spinner img element within its container div, the spinner is always displayed, which is not desired: https ...

Utilizing Angular to integrate with an external API

I have encountered an issue while trying to connect to the Expedia API. In order to do so, I need an API key and ID. Initially, I utilized JSONP for this connection but ran into a bug causing problems. Additionally, storing my API key in JavaScript poses ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

Uncovering the hidden gems within a data attribute

Trying my best to explain this clearly. What I have is a data-attribute that holds a large amount of data. In this case, I need to extract each individual basket product ID and display them as separate strings. The challenging part for me is locating thi ...

Using React.js to create a modal that includes ExpansionPanelDetails with a Checkbox feature

I am trying to achieve a specific visual effect with my code. Here is an example of the effect I want: https://i.stack.imgur.com/cJIxS.png However, the result I currently get looks like this: https://i.stack.imgur.com/547ND.png In the image provided, y ...

Need a jQuery callback function in PHP that only retrieves the value without any redirection

Initially, I expected this task to be simple but it turns out my skills are a bit rusty. The snippet of javascript/jquery code that I am using is: $.get("plugin.php", {up_vote:surl}, function(data){ //alert(data); document.getElementById(&apo ...

Skipping every third index in a JQuery .each loop after removing an element

I have a project where I need to display elements in rows of 4, and when an element is deleted, I want the remaining elements to shift up. To achieve this, I am currently assigning a class "last" to every fourth item after a deletion and inserting a spacer ...

Export all entries without taking into account pagination limits

My current setup involves using Datatables with pagination. I recently integrated the Datatable.buttons library to enable an Export to Excel feature. However, I encountered a limitation where only the first 10 rows on the current page are exported due to p ...

Error: A SyntaxError was encountered due to a missing closing parenthesis after an argument list while writing JavaScript within PHP code

I'm facing an issue writing JavaScript within PHP code. Here's my script : echo ' <script>'; echo ' $(function(){'; echo ' x = parseInt($("#counter2").val());'; echo ' $("#add_row2").click(function(){&apo ...

Creating a variable by utilizing $index values within two nested v-for loops

For my project, I am attempting to organize the days of a month into a table using 2 v-for loops. To simplify my code, I am considering creating a t_index variable that would be equal to ((r_index - 1) * 7 + c_index) - 2, but I am unsure how to implement ...

"Encountering difficulties while trying to modify the QuillNoSSRWrapper value within a Reactjs

Currently, I am working on a project involving ReactJS and I have opted to use the Next.js framework. As of now, I am focused on implementing the "update module" (blog update) functionality with the editor component called QuillNoSSRWrapper. The issue I ...

Error encountered: Provider '$rootScopeProvider' is not recognized - check for typos in the syntax

I am encountering an issue with the templateUrl in AngularJS. When I input this code into my editor and execute it, everything works flawlessly: HTML: <!DOCTYPE html> <html lang= "en"> <head> <meta charset="UTF-8" /> < ...

What could be causing the issue with HTML not being printed upon button click in ReactJS?

My goal is to display the word "Hello" on the screen when the add button is clicked. However, I am encountering an issue where it is not showing up. Any insights or solutions would be greatly appreciated! import React, { Component } from 'react'; ...

Randomly injecting strings like 'jQuery111201xxx' into a string using jQuery Ajax

After implementing a booking system that utilizes FullCalendar, I encountered an unusual issue with the 'notes' field. Occasionally, a strange string is inserted into the notes field at random points. Here's an example of what I found recent ...