@@ -10,29 +10,39 @@ 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 ) ] ;
14
- let i = left ;
13
+ const pivotIndex = choosePivot ( left , right ) ;
14
+ const pivot = array [ pivotIndex ] ;
15
+ [ array [ pivotIndex ] , array [ right ] ] = [ array [ right ] , array [ pivotIndex ] ] ;
16
+ let i = left - 1 ;
15
17
let j = right ;
16
18
17
- while ( i <= j ) {
18
- while ( array [ i ] < pivot ) {
19
- i ++ ;
20
- }
21
-
22
- while ( array [ j ] > pivot ) {
23
- j -- ;
24
- }
19
+ while ( i < j ) {
20
+ while ( array [ ++ i ] < pivot ) ;
21
+ while ( array [ -- j ] > pivot ) ;
25
22
26
- if ( i <= j ) {
23
+ if ( i < j ) {
27
24
[ array [ i ] , array [ j ] ] = [ array [ j ] , array [ i ] ] ;
28
- i ++ ;
29
- j -- ;
30
25
}
31
26
}
32
27
28
+ [ array [ right ] , array [ i ] ] = [ array [ i ] , array [ right ] ] ;
33
29
return i ;
34
30
} ;
35
31
32
+ /**
33
+ * @function choosePivot
34
+ * @description Chooses a pivot element randomly within the subarray.
35
+ * @param {number } left - The left index of the subarray.
36
+ * @param {number } right - The right index of the subarray.
37
+ * @returns {number } - The index of the chosen pivot element.
38
+ */
39
+ const choosePivot = (
40
+ left : number ,
41
+ right : number
42
+ ) : number => {
43
+ return Math . floor ( Math . random ( ) * ( right - left + 1 ) ) + left ;
44
+ } ;
45
+
36
46
/**
37
47
* Quicksort implementation
38
48
*
@@ -56,17 +66,15 @@ export const QuickSort = (
56
66
left : number = 0 ,
57
67
right : number = array . length - 1
58
68
) => {
59
- let index ;
60
-
61
69
if ( array . length > 1 ) {
62
- index = partition ( array , left , right ) ;
70
+ const index = partition ( array , left , right ) ;
63
71
64
72
if ( left < index - 1 ) {
65
73
QuickSort ( array , left , index - 1 ) ;
66
74
}
67
75
68
- if ( index < right ) {
69
- QuickSort ( array , index , right ) ;
76
+ if ( index + 1 < right ) {
77
+ QuickSort ( array , index + 1 , right ) ;
70
78
}
71
79
}
72
80
0 commit comments