forked from TheAlgorithms/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.ts
More file actions
74 lines (63 loc) · 1.62 KB
/
Copy pathQuickSort.ts
File metadata and controls
74 lines (63 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @function quickSort
* @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
* @see [Quick Sort](https://www.javatpoint.com/quick-sort)
* @example QuickSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
*/
export const partition = (
array: number[],
left: number = 0,
right: number = array.length - 1
) => {
const pivot = array[Math.floor((right + left) / 2)];
let i = left;
let j = right;
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
[array[i], array[j]] = [array[j], array[i]];
i++;
j--;
}
}
return i;
};
/**
* Quicksort implementation
*
* @param {number[]} array
* @param {number} [left=0]
* @param {number} [right=array.length - 1]
* @returns {number[]}
* @complexity_analysis
* Space complexity - O(nlogn)
* Time complexity
* Best case - O(nlogn)
* When pivot element lies in the middle of the list
* Worst case - O(n^2)
* When pivot element lies on the extreme ends
* Average case - O(nlogn)
* When the above two cases are not met
*/
export const QuickSort = (
array: number[],
left: number = 0,
right: number = array.length - 1
) => {
let index;
if (array.length > 1) {
index = partition(array, left, right);
if (left < index - 1) {
QuickSort(array, left, index - 1);
}
if (index < right) {
QuickSort(array, index, right);
}
}
return array;
};