Skip to content

QuickSort Algorithm in JavaScript #284

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

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
31 changes: 31 additions & 0 deletions Sorting/QuickSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/* QuickSort works by picking a pivot and dividing the list in relation to that pivot:
all elements greater than the pivot go to the right of the pivot,
and all elements less than or equal to the pivot go to the left of the pivot.
Elements on both sides are quick sorted, and this is repeated until the complete list is sorted.
*/

function quickSort(list) {
if (list.length <= 1) {
return list
} else {
const left = []
const right = []
const sorted = []
const pivot = list.pop() // we're picking the last item to act as the pivot
const length = list.length

for (let i = 0; i < length; i++) {
if (list[i] <= pivot) {
left.push(list[i])
} else {
right.push(list[i])
}
}

return sorted.concat(quickSort(left), pivot, quickSort(right))
}
}

const list = [0,85,64,21,36]
const sorted = quickSort(list)
console.log(sorted)