File tree Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ export const partition = (
10
10
left : number = 0 ,
11
11
right : number = array . length - 1
12
12
) => {
13
- const pivot = array [ Math . floor ( ( right + left ) / 2 ) ] ;
13
+ const pivot = array [ choosePivot ( left , right ) ] ;
14
14
let i = left ;
15
15
let j = right ;
16
16
@@ -33,6 +33,20 @@ export const partition = (
33
33
return i ;
34
34
} ;
35
35
36
+ /**
37
+ * @function choosePivot
38
+ * @description Chooses a pivot element randomly within the subarray.
39
+ * @param {number } left - The left index of the subarray.
40
+ * @param {number } right - The right index of the subarray.
41
+ * @returns {number } - The index of the chosen pivot element.
42
+ */
43
+ const choosePivot = (
44
+ left : number ,
45
+ right : number
46
+ ) : number => {
47
+ return Math . floor ( Math . random ( ) * ( right - left + 1 ) ) + left
48
+ } ;
49
+
36
50
/**
37
51
* Quicksort implementation
38
52
*
@@ -55,7 +69,7 @@ export const QuickSort = (
55
69
array : number [ ] ,
56
70
left : number = 0 ,
57
71
right : number = array . length - 1
58
- ) => {
72
+ ) : number [ ] => {
59
73
let index ;
60
74
61
75
if ( array . length > 1 ) {
You can’t perform that action at this time.
0 commit comments