This repository has been archived by the owner on Feb 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* 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
1 parent
2c3a084
commit 8eb3645
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |