Skip to content

Commit 86fc7a5

Browse files
committed
adds quick sort
1 parent 141d73f commit 86fc7a5

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

quickSort/index.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const { printArray } = require('../utils')
2+
3+
function quickSort(array) {
4+
printArray(array)
5+
6+
if (array.length < 2) {
7+
return array
8+
}
9+
10+
const pivotIndex = array.length - 1
11+
const pivot = array[pivotIndex]
12+
const left = []
13+
const right = []
14+
15+
for (let i = 0; i < pivotIndex; i++) {
16+
const item = array[i]
17+
item < pivot ? left.push(item) : right.push(item)
18+
}
19+
20+
return [...quickSort(left), pivot, ...quickSort(right)]
21+
}
22+
23+
exports.quickSort = quickSort

quickSort/index.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
const { quickSort } = require('./index')
2+
3+
test('Quick Sort', () => {
4+
const nums = [10, 8, 4, 3, 6, 2, 1, 9, 7, 5]
5+
expect(quickSort(nums)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
6+
})

quickSort/script.md

Whitespace-only changes.

0 commit comments

Comments
 (0)