Open In App

Sorting Tricks in Node.js

Sorting an array using the timer class:

Approach: The sorting requires visiting each element and then performing some operations, which requires for loop to visit those elements.



Now here, we can use setInterval() method to visit all those elements, and perform those operations. And during the visit, we can use setTimer() method to visit all elements, and print the minimum of the array during that period of time.

The setInterval() method repeats or re-schedules the given function at every given time-interval. It is somewhat like window.setInterval() method of JavaScript API, however, a string of code can’t be passed to get it executed.



Syntax:

setInterval(timerFunction, millisecondsTime);

Parameters: It accepts two parameters which are mentioned above and described below:

The setTimeout() method is used to schedule code execution after waiting for a specified number of milliseconds. It is somewhat like window.setTimeout() Method of JavaScript API, however a string of code can’t be passed to get it executed.

Syntax:

setTimeout(timerFunction, millisecondsTime);

Parameter: It accepts two parameters which are mentioned above and described below:

Examples:

Input: Array = [ 46, 55, 2, 100, 0, 500 ]
Output: [0, 2, 46, 55, 100, 500]

Input: Array = [8, 9, 2, 7, 18, 5, 25]
Output: [ 2, 5, 7, 8, 9, 18, 25 ]

Example 1: File Name: Index.js




const arr = [10, 50, 100, 500, 0, 200];
var arr1 = [];
  
function sortIt() {
for (let i of arr) {
  
 // setTimeout(()=> console.log(i), i)
  
 setTimeout(()=> {
     
   arr1.push(i);
   arr.splice(arr.indexOf(i), 1);
   if(arr.length === 0){
     console.log(arr1);
   }
 }, i)
}}
  
sortIt();

Output:

[ 0, 10, 50, 100, 200, 500 ]

Example 2: File Name: Index.js




const arr = [10, 50, 100, 500, 0, 200];
var arr1 = [];
  
function sortIt() {
   for (let i of arr) {
     // setTimeout(()=> console.log(i), i)
     setTimeout(()=> {
     
        arr1.push(i);
        i = Math.max.apply(null, arr);
          
        // arr.splice(arr.indexOf(i), 1);
        if(arr1.length === arr.length) {
           console.log(arr1);
        }
     }, i)
}}
  
sortIt();

Run Index.js File using the below command.

node index.js

Output:

[ 0, 10, 50, 100, 200, 500 ]

Article Tags :