From dc7cd15800382b342117fc7af9515736f30f53a4 Mon Sep 17 00:00:00 2001 From: Priya Ranjan Dubey Date: Thu, 31 Oct 2019 11:05:06 +0530 Subject: [PATCH] QuickSort Algorithm in JavaScript --- Sorting/QuickSort.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Sorting/QuickSort.js diff --git a/Sorting/QuickSort.js b/Sorting/QuickSort.js new file mode 100644 index 0000000..5f87cc4 --- /dev/null +++ b/Sorting/QuickSort.js @@ -0,0 +1,31 @@ +/* QuickSort works by picking a pivot and dividing the list in relation to that pivot: +all elements greater than the pivot go to the right of the pivot, +and all elements less than or equal to the pivot go to the left of the pivot. +Elements on both sides are quick sorted, and this is repeated until the complete list is sorted. +*/ + +function quickSort(list) { + if (list.length <= 1) { + return list + } else { + const left = [] + const right = [] + const sorted = [] + const pivot = list.pop() // we're picking the last item to act as the pivot + const length = list.length + + for (let i = 0; i < length; i++) { + if (list[i] <= pivot) { + left.push(list[i]) + } else { + right.push(list[i]) + } + } + + return sorted.concat(quickSort(left), pivot, quickSort(right)) + } +} + +const list = [0,85,64,21,36] +const sorted = quickSort(list) +console.log(sorted) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy