Skip to content
This repository has been archived by the owner on Feb 21, 2021. It is now read-only.

Commit

Permalink
Restyle Quick sort in js (#50)
Browse files Browse the repository at this point in the history
* Quick sort in js

* Added test case for quick sort

* Restyled by clang-format

* Restyled by prettier

Co-authored-by: kheenvraj <[email protected]>
Co-authored-by: Restyled.io <[email protected]>
  • Loading branch information
3 people authored Oct 23, 2020
1 parent 2c3a084 commit 8eb3645
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Sorting/quick_sort/quick_sort.js
Original file line number Diff line number Diff line change
@@ -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;
}
8 changes: 8 additions & 0 deletions Sorting/quick_sort/quick_sort.test.js
Original file line number Diff line number Diff line change
@@ -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);

0 comments on commit 8eb3645

Please sign in to comment.