Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
17 changes: 17 additions & 0 deletions src/sort/quick/quickSort.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import quickSort from './quickSort';

describe('quick sort', () => {
it('It should return an array sorted from lowest to highest', () => {
Comment thread
hugovenega marked this conversation as resolved.
Outdated
Comment thread
hugovenega marked this conversation as resolved.
Outdated
const arrayToSort = [43, 65, 44, 12, 67, 1, 9, 33, 21];
const expectedArray = [1, 9, 12, 21, 33, 43, 44, 65, 67];
expect(quickSort(arrayToSort, (a: number, b: number): boolean => (a < b)))
Comment thread
hugovenega marked this conversation as resolved.
Outdated
.toEqual(expectedArray);
});

it('It should return an array sorted from highest to lowest', () => {
const arrayToSort = [43, 65, 44, 12, 67, 1, 9, 33, 21];
const expectedArray = [67, 65, 44, 43, 33, 21, 12, 9, 1];
expect(quickSort(arrayToSort, (a: number, b: number): boolean => (a > b)))
Comment thread
hugovenega marked this conversation as resolved.
Outdated
.toEqual(expectedArray);
});
});
29 changes: 29 additions & 0 deletions src/sort/quick/quickSort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
interface CompareFunction {
(a: number, b: number): boolean;
}

export default function quickSort(array: number[], compareFunction:CompareFunction): number[] {
if (array.length < 2) {
return array;
}
const pivot = array[Math.floor(Math.random() * array.length)];

const left: number[] = [];
const right: number[] = [];
const equal: number[] = [];

array.forEach((value) => {
if (compareFunction(value, pivot)) {
left.push(value);
} else if (!compareFunction(value, pivot)) {
right.push(value);
} else {
equal.push(value);
}
});
return [
...quickSort(left, compareFunction),
...equal,
...quickSort(right, compareFunction),
];
}