forked from TheAlgorithms/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.ts
More file actions
79 lines (69 loc) · 2.11 KB
/
Copy pathquick_sort.ts
File metadata and controls
79 lines (69 loc) · 2.11 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
75
76
77
78
79
/**
* @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 pivotIndex = choosePivot(left, right)
const pivot = array[pivotIndex]
;[array[pivotIndex], array[right]] = [array[right], array[pivotIndex]]
let i = left - 1
let j = right
while (i < j) {
while (array[++i] < pivot);
while (array[--j] > pivot);
if (i < j) {
;[array[i], array[j]] = [array[j], array[i]]
}
}
;[array[right], array[i]] = [array[i], array[right]]
return i
}
/**
* @function choosePivot
* @description Chooses a pivot element randomly within the subarray.
* @param {number} left - The left index of the subarray.
* @param {number} right - The right index of the subarray.
* @returns {number} - The index of the chosen pivot element.
*/
const choosePivot = (left: number, right: number): number => {
return Math.floor(Math.random() * (right - left + 1)) + left
}
/**
* 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
) => {
if (array.length > 1) {
const index = partition(array, left, right)
if (left < index - 1) {
QuickSort(array, left, index - 1)
}
if (index + 1 < right) {
QuickSort(array, index + 1, right)
}
}
return array
}