From 56a12bc25040a1051aaca1988f61f8b0b37f2997 Mon Sep 17 00:00:00 2001 From: Hemang Pandey <72122821+Hemangpandey@users.noreply.github.com> Date: Tue, 27 Apr 2021 22:41:17 +0530 Subject: [PATCH] chore(JavaScript): quick sort added (#270) --- algorithms/JavaScript/README.md | 5 +- algorithms/JavaScript/src/index.js | 2 + .../JavaScript/src/sorting/quick-sort.js | 46 +++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 algorithms/JavaScript/src/sorting/quick-sort.js diff --git a/algorithms/JavaScript/README.md b/algorithms/JavaScript/README.md index 430e8639..dfcda5f4 100644 --- a/algorithms/JavaScript/README.md +++ b/algorithms/JavaScript/README.md @@ -14,8 +14,9 @@ ## Sorting 1. [Bubble Sort](src/sorting/bubble-sort.js) 2. [Insertion Sort](src/sorting/insertion-sort.js) -3. [Selection Sort](src/sorting/selection-sort.js) -4. [Merge Sort](src/sorting/merge-sort.js) +3. [Merge Sort](src/sorting/merge-sort.js) +4. [Quick Sort](src/sorting/quick-sort.js) +5. [Selection Sort](src/sorting/selection-sort.js) ## Strings 1. [Palindrome](src/strings/palindrome.js) diff --git a/algorithms/JavaScript/src/index.js b/algorithms/JavaScript/src/index.js index 78997e09..214b8f7f 100644 --- a/algorithms/JavaScript/src/index.js +++ b/algorithms/JavaScript/src/index.js @@ -12,6 +12,8 @@ require('./searching/linear-search'); // Sorting require('./sorting/bubble-sort'); require('./sorting/insertion-sort'); +require('./sorting/merge-sort'); +require('./sorting/quick-sort'); require('./sorting/selection-sort'); // Strings diff --git a/algorithms/JavaScript/src/sorting/quick-sort.js b/algorithms/JavaScript/src/sorting/quick-sort.js new file mode 100644 index 00000000..11613198 --- /dev/null +++ b/algorithms/JavaScript/src/sorting/quick-sort.js @@ -0,0 +1,46 @@ +function swap(items, leftIndex, rightIndex) { + const temp = items[leftIndex]; + items[leftIndex] = items[rightIndex]; + items[rightIndex] = temp; +} + +function partition(items, left, right) { + const pivot = items[Math.floor((right + left) / 2)]; // middle element + let i = left; // left pointer + let j = right; // right pointer + while (i <= j) { + while (items[i] < pivot) { + i++; + } + while (items[j] > pivot) { + j--; + } + if (i <= j) { + swap(items, i, j); // sawpping two elements + i++; + j--; + } + } + return i; +} + +function quickSort(items, left, right) { + let index; + if (items.length > 1) { + index = partition(items, left, right); // index returned from partition + if (left < index - 1) { + // more elements on the left side of the pivot + quickSort(items, left, index - 1); + } + if (index < right) { + // more elements on the right side of the pivot + quickSort(items, index, right); + } + } + return items; +} + +// first call to quick sort +const items = [5, 3, 7, 6, 2, 9]; +const sortedArray = quickSort(items, 0, items.length - 1); +console.log(sortedArray); // prints [2,3,5,6,7,9]