- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting an array of literals using quick sort in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and uses the quick sort algorithm to sort it.
QuickSort:
This algorithm is basically a divide and conquer algorithm where we pick a pivot in every pass of loop and put all the elements smaller than pivot to its left and all greater than pivot to its right (if its ascending sort otherwise opposite)
Example
The code for this will be −
const arr = [43, 3, 34, 34, 23, 232, 3434, 4, 23, 2, 54, 6, 54]; // Find a "pivot" element in the array to compare all other // elements against and then shift elements before or after // pivot depending on their values const quickSort = (arr, left = 0, right = arr.length - 1) => { let len = arr.length, index; if(len > 1) { index = partition(arr, left, right) if(left < index - 1) { quickSort(arr, left, index - 1) } if(index < right) { quickSort(arr, index, right) } } return arr } const partition = (arr, left, right) => { let middle = Math.floor((right + left) / 2), pivot = arr[middle], i = left, // Start pointer at the first item in the array j = right // Start pointer at the last item in the array while(i <= j) { // Move left pointer to the right until the value at the // left is greater than the pivot value while(arr[i] < pivot) { i++ } // Move right pointer to the left until the value at the // right is less than the pivot value while(arr[j] > pivot) { j-- } // If the left pointer is less than or equal to the // right pointer, then swap values if(i <= j) { [arr[i], arr[j]] = [arr[j], arr[i]] // ES6 destructuring swap i++ j-- } } return i } console.log(quickSort(arr));
Output
The output in the console −
[ 2, 3, 4, 6, 23, 23, 34, 34, 43, 54, 54, 232, 3434 ]
- Related Articles
- Sorting Array without using sort() in JavaScript
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Merge sort vs quick sort in Javascript
- Sorting arrays using bubble sort in JavaScript
- Randomly shuffling an array of literals in JavaScript
- Alternative sorting of an array in JavaScript
- Sorting an array of objects by an array JavaScript
- How to implement quick sort in JavaScript?
- Using merge sort to recursive sort an array JavaScript
- Sorting and find sum of differences for an array using JavaScript
- Sorting an array of binary values - JavaScript
- Quick Sort
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Sorting an array that contains the value of some weights using JavaScript

Advertisements