From 781913b8d055e6c2304b28d685ff8487fc3f4377 Mon Sep 17 00:00:00 2001 From: Panzki Date: Fri, 29 Sep 2017 21:34:28 +0200 Subject: [PATCH] Added quicksort to the sorting algorithms. --- Sorts/quickSort.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Sorts/quickSort.js diff --git a/Sorts/quickSort.js b/Sorts/quickSort.js new file mode 100644 index 000000000..979893890 --- /dev/null +++ b/Sorts/quickSort.js @@ -0,0 +1,38 @@ +/* +* Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy. +* For more information see here: https://en.wikipedia.org/wiki/Quicksort +*/ +function quickSort(items) { + + var length = items.length; + + if (length <= 1) { + return items; + } + var PIVOT = items[0]; + var GREATER = []; + var LESSER = []; + + for (var i = 1; i < length; i++) { + if (items[i] > PIVOT) { + GREATER.push(items[i]); + } else { + LESSER.push(items[i]); + } + } + + var sorted = quickSort(LESSER); + sorted.push(PIVOT); + sorted = sorted.concat(quickSort(GREATER)); + + return sorted; +} + +//Implementation of quick sort + +var ar = [0, 5, 3, 2, 2]; +//Array before Sort +console.log(ar); +ar = quickSort(ar); +//Array after sort +console.log(ar);