From 8eb36456f5ad86afd767f9b5f4091c04c58fb538 Mon Sep 17 00:00:00 2001 From: "restyled-io[bot]" <32688539+restyled-io[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2020 17:46:45 +0530 Subject: [PATCH] Restyle Quick sort in js (#50) * Quick sort in js * Added test case for quick sort * Restyled by clang-format * Restyled by prettier Co-authored-by: kheenvraj Co-authored-by: Restyled.io --- Sorting/quick_sort/quick_sort.js | 48 +++++++++++++++++++++++++++ Sorting/quick_sort/quick_sort.test.js | 8 +++++ 2 files changed, 56 insertions(+) create mode 100644 Sorting/quick_sort/quick_sort.js create mode 100644 Sorting/quick_sort/quick_sort.test.js diff --git a/Sorting/quick_sort/quick_sort.js b/Sorting/quick_sort/quick_sort.js new file mode 100644 index 0000000..76ff0d7 --- /dev/null +++ b/Sorting/quick_sort/quick_sort.js @@ -0,0 +1,48 @@ +// Quick sort algorithm in JS. +/** + @param {Array} arr Input array. + @param {Number} left Input array. + @param {Number} right Input array. + @return {Array} Sorted array. +*/ + +module.exports = { + quickSort: (arr, left, right) => { + let pivot, partitionIndex; + + if (left < right) { + pivot = right; + partitionIndex = partition(arr, pivot, left, right); + + // sort left and right + quickSort(arr, left, partitionIndex - 1); + quickSort(arr, partitionIndex + 1, right); + } + return arr; + }, +}; + +/** + * This function keep move all the items smaller than the pivot value to the + * left and larger than pivot value to the right + */ +function partition(arr, pivot, left, right) { + let pivotValue = arr[pivot], + partitionIndex = left; + + for (let i = left; i < right; i++) { + if (arr[i] < pivotValue) { + swap(arr, i, partitionIndex); + partitionIndex++; + } + } + swap(arr, right, partitionIndex); + return partitionIndex; +} + +/** This function to swap values of the array. */ +function swap(arr, i, j) { + let temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} diff --git a/Sorting/quick_sort/quick_sort.test.js b/Sorting/quick_sort/quick_sort.test.js new file mode 100644 index 0000000..c2c7a7c --- /dev/null +++ b/Sorting/quick_sort/quick_sort.test.js @@ -0,0 +1,8 @@ +// Test case of quick sort function. +const quick_sort_test = require("./quick_sort.js"); + +const input = [11, 8, 14, 3, 6, 2, 7]; +const left = 0; +const right = 6; +const sorted = quick_sort_test.quickSort(input, left, right); +console.log("Quick sort output: ", sorted);