From 82820dca6ccb92ae56dcc7cf090b6f769019be2a Mon Sep 17 00:00:00 2001 From: DHRUVKADAM22 <147514863+DHRUVKADAM22@users.noreply.github.com> Date: Sat, 28 Oct 2023 13:14:23 +0530 Subject: [PATCH] Create Quicksort.js added quick sort an sorting method in DSA --- DSA/Arrays/Quicksort.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 DSA/Arrays/Quicksort.js diff --git a/DSA/Arrays/Quicksort.js b/DSA/Arrays/Quicksort.js new file mode 100644 index 0000000..1b07757 --- /dev/null +++ b/DSA/Arrays/Quicksort.js @@ -0,0 +1,29 @@ +function quickSort(arr) { + if (arr.length <= 1) { + return arr; + } + + const pivotIndex = Math.floor(arr.length / 2); + const pivot = arr[pivotIndex]; + + const left = []; + const right = []; + + for (let i = 0; i < arr.length; i++) { + if (i === pivotIndex) { + continue; + } + if (arr[i] < pivot) { + left.push(arr[i]); + } else { + right.push(arr[i]); + } + } + + return [...quickSort(left), pivot, ...quickSort(right)]; +} + +// Example usage: +const unsortedArray = [5, 3, 7, 2, 8, 4, 1]; +const sortedArray = quickSort(unsortedArray); +console.log(sortedArray);