Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve space complexity of QuickSort algorithm #1704

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 46 additions & 15 deletions Sorts/QuickSort.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,61 @@
/**
* @function QuickSort
* @description Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy.
* It sorts the array in place by using a partitioning technique instead of creating separate arrays.
* @param {Integer[]} items - Array of integers
* @param {Integer} left - Starting index
* @param {Integer} right - Ending index
* @return {Integer[]} - Sorted array.
* @see [QuickSort](https://en.wikipedia.org/wiki/Quicksort)
*/
function quickSort(items) {
const length = items.length

if (length <= 1) {
function quickSort(items, left = 0, right = items.length - 1) {
if (left >= right) {
return items
}
const PIVOT = items[0]
const GREATER = []
const LESSER = []

for (let i = 1; i < length; i++) {
if (items[i] > PIVOT) {
GREATER.push(items[i])
} else {
LESSER.push(items[i])

const pivotIndex = partition(items, left, right)
quickSort(items, left, pivotIndex - 1)
quickSort(items, pivotIndex + 1, right)

return items
}

/**
* @function partition
* @description Partitions the array in place and returns the index of the pivot.
* @param {Integer[]} items - Array of integers
* @param {Integer} left - Starting index
* @param {Integer} right - Ending index
* @return {Integer} - Pivot index.
*/
function partition(items, left, right) {
const PIVOT = items[right] // Choose the rightmost element as pivot
let partitionIndex = left

for (let i = left; i < right; i++) {
if (items[i] < PIVOT) {
swap(items, i, partitionIndex)
partitionIndex++
}
}

const sorted = [...quickSort(LESSER), PIVOT, ...quickSort(GREATER)]
return sorted
// Move the pivot to its correct position
swap(items, partitionIndex, right)

return partitionIndex
}

/**
* @function swap
* @description Helper function to swap two elements in the array.
* @param {Integer[]} items - Array of integers
* @param {Integer} i - Index of the first element
* @param {Integer} j - Index of the second element
*/
function swap(items, i, j) {
const temp = items[i]
items[i] = items[j]
items[j] = temp
}

export { quickSort }