Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a68373f

Browse files
authored
Create quick-sort-simple.js
1 parent a24341f commit a68373f

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

‎quick-sort-simple.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Note : This is not a in place quick sort; but example gives a good intuition about the algorithm
2+
// Credits : https://itnext.io/a-sort-of-quick-guide-to-quicksort-and-hoares-partitioning-scheme-in-javascript-7792112c6d1
3+
const quickSort = (arr) => {
4+
// base case; An array with less than 2 elements is always sorted
5+
if (arr.length <= 1) return arr;
6+
// Choose a random pivot
7+
const pivot = arr.splice(Math.floor(Math.random() * (arr.length - 1)), 1);
8+
const left = [];
9+
const right = [];
10+
// left has all the elements lesser than pivot; right has elements greater than pivot
11+
arr.forEach(el => el < pivot ? left.push(el) : right.push(el));
12+
// recursively call on the left and right arrays
13+
const sortedLeft = quickSort(left);
14+
const sortedRight = quickSort(right);
15+
// now combine the sortedLeft, pivot(remember it is sandwiched between left and right), sortedRight
16+
return [...sortedLeft, ...pivot, ...sortedRight];
17+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /