# Implementing Quicksort Algorithm in Javascript

We've been wanting to write an article about sorting algorithms for some time now because sometimes we forget how useful they can be when we want to optimize our code.
So yesterday we played with the quicksort algorithm in Javascript (one of the most efficient when you have to order arrays). In this article we will tell you all the process we have followed.

We hope it will be useful.

## Quicksort performance

Worst-case performance: O(n^2)

Best-case performance: O(n log n)

Average performance: O(n log n)

Not bad considering that the bubble sort has an average O(n^2)

## How does Quicksort work?

Quicksort works by choosing an element from the array that we'll call a pivot so we can divide the initial array in two:

- the major ones with respect to it

- the minors with respect to it

placing this pivot element in the middle after the separation.

Now for each of these two arrays we will choose a pivot again and repeat the same procedure. There will come a time when the resulting arrays will have either one element or none if there is no longer an element to compare them with. The rest of the elements will have been separated as pivots in some point of the algorithm and they will already be in their correct position.

## How do we implement Quicksort?

To implement the quicksort algorithm in javascript we will rely on the pseudocode taken from wikipedia:

```algorithm quicksort(A, lo, hi) is
if lo < hi then
p := partition(A, lo, hi)
quicksort(A, lo, p - 1)
quicksort(A, p + 1, hi)
algorithm partition(A, lo, hi) is
pivot := A[hi]
i := lo
for j := lo to hi - 1 do
if A[j] < pivot then
swap A with A[j]
i := i + 1
swap A with A[hi]
return i
```

The first thing we'll do is define the function that executes the algorithm. Since we want to be able to sort all types of arrays (not only numbers, but also objects) we will allow the function to receive by arguments an additional function that specifies the method of sorting objects:

```const defaultSortingAlgorithm = (a, b) => {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
};
const quickSort = (
unsortedArray,
sortingAlgorithm = defaultSortingAlgorithm
) => {
// quicksort implementation
};
```

If we look at the pseudocode of the wikipedia, we see that as initial pivot is choosing the end of the array (this can cause performance problems increasing it to O(n^2) when the array is already ordered) so not to complicate too much the article we will focus on him. Also, notice that the pseudocode is written in recursive form since we do not know how many partitions we will have to do as we order the array. With all this we come to:

```const defaultSortingAlgorithm = (a, b) => {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
};
const quickSort = (
unsortedArray,
sortingAlgorithm = defaultSortingAlgorithm
) => {
// immutable version
const sortedArray = [...unsortedArray];
const swapArrayElements = (arrayToSwap, i, j) => {
const a = arrayToSwap;
arrayToSwap = arrayToSwap[j];
arrayToSwap[j] = a;
};
const partition = (arrayToDivide, start, end) => {
const pivot = arrayToDivide[end];
let splitIndex = start;
for (let j = start; j <= end - 1; j++) {
const sortValue = sortingAlgorithm(arrayToDivide[j], pivot);
if (sortValue === -1) {
swapArrayElements(arrayToDivide, splitIndex, j);
splitIndex++;
}
}
swapArrayElements(arrayToDivide, splitIndex, end);
return splitIndex;
};
// Recursively sort sub-arrays.
const recursiveSort = (arraytoSort, start, end) => {
// stop condition
if (start < end) {
const pivotPosition = partition(arraytoSort, start, end);
recursiveSort(arraytoSort, start, pivotPosition - 1);
recursiveSort(arraytoSort, pivotPosition + 1, end);
}
};
// Sort the entire array.
recursiveSort(sortedArray, 0, unsortedArray.length - 1);
return sortedArray;
};
```

As you can see, the first thing we do is clone the array so that the function is immutable and we don't modify the input array. From there we define 3 methods:

swapArrayElements: para intercambiar los elementos de un array

partition: que se encarga de elegir el pivote e intercambiar los elementos para que los más grandes estén a su derecha y los más pequeños a su izquierda. Como se puede ver, hacemos la comparación con el método de clasificación que hemos aprobado o con el que hemos establecido por defecto. Este método devuelve la posición en la que se dejó el pivot.

recursiveSort : implementa el algoritmo quicksort definido en wikipedia. Se debe tener en cuenta que es necesario configurar la condición de parada inicio < fin para que de esta forma se interrumpa la recursión si se han alcanzado arrays de 0 ó 1 elementos.

Finally, the quickSort method invokes recursiveSort by passing it the array as well as the initial and final position.
With this we would already have the quicksort algorithm working in javascript:

```const testA = [9, -3, 5, 2, 6, 8, -6, 1, 3];
const testASorted = quickSort(testA);
console.log(testASorted);
const testB = [-3, -2, -1, 0, 1, 2, 3];
const testBSorted = quickSort(testB);
console.log(testBSorted);
const testC = [3, 2, 1, 0, -1, -2, -3];
const testCSorted = quickSort(testC);
console.log(testCSorted);
const testD = [
{
id: 9,
},
{
id: -1,
},
{
id: 5,
},
{
id: 3,
},
{
id: -10,
}
];
const testDSorted = quickSort(testD, (a, b) => {
if (a.id < b.id) {
return -1;
}
if (a.id > b.id) {
return 1;
}
return 0;
});
console.log(testDSorted);
```

by admin admin Date: 16-08-2019 javascript coding functions webdev quicksort hits : 2906

### Related Posts

#### Cross-Origin Resource Sharing (CORS) and examples of XSS and CSRF

Cross-Origin Resource Sharing (CORS) enables web clients to make HTTP requests to servers hosted on different origins. CORS is a unique web technology in that it has both a server-side…

#### How to Generate Static Sites with JavaScript Static Sites Generators

Static websites and so-called JAMstack have become pretty popular recently. And with 2020 on the horizon, this trend doesn't seem to be stopping. Why? Why is old-school HTML + CSS…

If you have your own business, or you are working towards launching one, chances are you’ve thought about building your own website. A strong, professional website is essential for businesses…

#### What is Webpack and how does it work

WebPack is basically a packer of modules or module bundler, but thanks to one of its components, the plugins, can be used as tasks runner, ie we can do tasks…

#### Angular vs React vs Vue: Which is the Best Choice?

With the growing popularity of Vue, Angular and React as frameworks and libraries for the web and app development, a constant doubt is which of these 3 we should learn,…

#### CRUD Operations Using Vue.js: a basic example

In this tutorial, we show you how to create CRUD application using vue js. here is very basic and simple example of vue.js crud app. using this vuejs crud (create…

#### Why is React so popular as a JavaScript library?

If you want to know why React is so successful as a JavaScript library, we need to talk about its main features to find out what it is currently used…

#### Javascript overcomes Java as the most popular programming language of 2019

The competition between Java and Javascript (in terms of popularity, not in use) has been going on for years. But it seems that Javascript is gradually consolidating as the most…

#### Vue.js 3.0: What are Hooks and how they work

This article introduces an experimental Vue feature called Hooks. Before you start This post is suited for developers of all stages including beginners. Here are a few things you should already have…

#### What's new in Angular?

In version 8.0.3 of Angular we can find great changes and say goodbye to our beloved companion the home page of Angular which has been re-designed with a fresh attractive…

#### React: 4 types of components to rule them all

If you have already worked with React, you will probably have found terms like "dumb components", "stateless components" or "high order components" which serve to describe different ways of defining…

#### How To Disable Right Button of Mouse in Web Pages

In this snippet we are going to see how to block the right mouse button to prevent the user from taking out the context menu. This is good because in…