Implementing the Quicksort API

First, let's create the Quicksort class, which will sort the elements based on the pivot as the first element in the set passed. Let's create a file called quick.js under the sort folder:

class Quick {

simpleSort(data) {

// if only one element exists
if(data.length < 2) {
return data;
}

// first data point is the pivot
const pivot = data[0];

// initialize low and high values
const low = [];
const high = [];

// compare against pivot and add to
// low or high values
for(var i = 1; i < data.length; i++) {

// interchange condition to reverse sorting
if(data[i].pages > pivot.pages) {
low.push(data[i]);
} else {
high.push(data[i]);
}
}

// recursively sort and concat the
// low values, pivot and high values
return this.simpleSort(low)
.concat(pivot, this.simpleSort(high));
}

}


module.exports = Quick;

That was straightforward, now, let's quickly add the endpoint to access this algorithm to sort our books and return them to the requested user:

var express = require('express');
var app = express();
var data = require('./books.json');
var Insertion = require('./sort/insertion');
var Merge = require('./sort/merge');
var Quick = require('./sort/quick');


....


app.get('/quick', function (req, res) {
res.status(200).send(new Quick().simpleSort(data));
});


app.listen(3000, function () {
console.log('Chat Application listening on port 3000!')
});

Also, now, restart the server to access the new endpoint that is created. We can see here that the approach is not ideal as it is requesting additional memory to contain the low and the high values compared to the pivot.

So, instead, we can use the previously discussed Lomuto or Hoare Partition Schemes to perform this operation in memory and reduce the memory costs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.27.209