Skip to content

Commit ca9fd24

Browse files
authored
[Feat] : Added Quick Sort (#35)
1 parent e298f3a commit ca9fd24

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

Sorts/QuickSort.ts

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* @function quickSort
3+
* @description is an algorithm based on divide and conquer approach in which an array is split into sub-arrays and these sub arrays are recursively sorted to get final array
4+
* @see [Quick Sort](https://www.javatpoint.com/quick-sort)
5+
* @example QuickSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
6+
*/
7+
8+
export const partition = (
9+
array: number[],
10+
left: number = 0,
11+
right: number = array.length - 1
12+
) => {
13+
const pivot = array[Math.floor((right + left) / 2)];
14+
let i = left;
15+
let j = right;
16+
17+
while (i <= j) {
18+
while (array[i] < pivot) {
19+
i++;
20+
}
21+
22+
while (array[j] > pivot) {
23+
j--;
24+
}
25+
26+
if (i <= j) {
27+
[array[i], array[j]] = [array[j], array[i]];
28+
i++;
29+
j--;
30+
}
31+
}
32+
33+
return i;
34+
};
35+
36+
/**
37+
* Quicksort implementation
38+
*
39+
* @param {number[]} array
40+
* @param {number} [left=0]
41+
* @param {number} [right=array.length - 1]
42+
* @returns {number[]}
43+
* @complexity_analysis
44+
* Space complexity - O(nlogn)
45+
* Time complexity
46+
* Best case - O(nlogn)
47+
* When pivot element lies in the middle of the list
48+
* Worst case - O(n^2)
49+
* When pivot element lies on the extreme ends
50+
* Average case - O(nlogn)
51+
* When the above two cases are not met
52+
*/
53+
54+
export const QuickSort = (
55+
array: number[],
56+
left: number = 0,
57+
right: number = array.length - 1
58+
) => {
59+
let index;
60+
61+
if (array.length > 1) {
62+
index = partition(array, left, right);
63+
64+
if (left < index - 1) {
65+
QuickSort(array, left, index - 1);
66+
}
67+
68+
if (index < right) {
69+
QuickSort(array, index, right);
70+
}
71+
}
72+
73+
return array;
74+
};

Sorts/test/QuickSort.test.ts

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { QuickSort } from "../QuickSort";
2+
3+
describe("Quick Sort", () => {
4+
it("should return the correct value for average case", () => {
5+
expect(QuickSort([1, 4, 2, 5, 9, 6, 3, 8, 10, 7])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
6+
});
7+
8+
it("should return the correct value for worst case", () => {
9+
expect(QuickSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
10+
});
11+
12+
it("should return the correct value for best case", () => {
13+
expect(QuickSort([1, 4, 2, 9, 5, 7, 3, 8, 10, 6])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
14+
});
15+
});

0 commit comments

Comments
 (0)