Skip to content

Commit ce966cd

Browse files
committed
Added quicksort-js
1 parent ef7360d commit ce966cd

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

Quicksort-JS/question.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Sort the given by implementing Quicksort
2+
[2, 4, 1, 6, -7, 8, 5, 9, 3, 4]
3+
4+
answer:
5+
[ -7, 1, 2, 3, 4, 4, 5, 6, 8, 9 ]

Quicksort-JS/quickSort.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const myArray = [2, 4, 1, 6, -7, 8, 5, 9, 3, 4];
2+
3+
const quickSortV1 = arr => {
4+
if (arr.length <= 1) {
5+
return arr;
6+
}
7+
8+
// shift takes out the element of the array
9+
// so that it can reach the base case
10+
let pivot = arr.shift();
11+
let left = arr.filter(el => el < pivot);
12+
let right = arr.filter(el => el >= pivot);
13+
14+
let leftSorted = quickSortV1(left);
15+
let rightSorted = quickSortV1(right);
16+
17+
return [...leftSorted, pivot, ...rightSorted];
18+
19+
};
20+
21+
console.log(quickSortV1(myArray));

0 commit comments

Comments
 (0)