1+ // src/algorithms/sorting/quickSort.js
2+ export function * quickSort ( array ) {
3+ const arr = [ ...array ] ;
4+
5+ // Helper generator function for the recursive quicksort
6+ function * quickSortHelper ( low , high ) {
7+ if ( low < high ) {
8+ // Partition the array and get the pivot index
9+ yield * partition ( low , high ) ;
10+ const pivotIndex = arr . lastPivotIndex ;
11+
12+ // Recursively sort left subarray
13+ yield * quickSortHelper ( low , pivotIndex - 1 ) ;
14+
15+ // Recursively sort right subarray
16+ yield * quickSortHelper ( pivotIndex + 1 , high ) ;
17+ } else if ( low === high ) {
18+ // Single element is already sorted
19+ yield { type : "sorted" , index : low } ;
20+ }
21+ }
22+
23+ // Partition function using Lomuto partition scheme
24+ function * partition ( low , high ) {
25+ // Choose the last element as pivot
26+ const pivot = arr [ high ] ;
27+ yield { type : "pivot" , index : high } ;
28+
29+ let i = low - 1 ; // Index of smaller element
30+
31+ for ( let j = low ; j < high ; j ++ ) {
32+ // Highlight current partition range
33+ yield { type : "partition" , indices : [ low , high ] } ;
34+
35+ // Compare current element with pivot
36+ yield { type : "compare" , indices : [ j , high ] } ;
37+
38+ if ( arr [ j ] < pivot ) {
39+ i ++ ;
40+ if ( i !== j ) {
41+ // Swap elements
42+ [ arr [ i ] , arr [ j ] ] = [ arr [ j ] , arr [ i ] ] ;
43+ yield { type : "swap" , indices : [ i , j ] , array : [ ...arr ] } ;
44+ }
45+ }
46+ }
47+
48+ // Place pivot in its correct position
49+ if ( i + 1 !== high ) {
50+ [ arr [ i + 1 ] , arr [ high ] ] = [ arr [ high ] , arr [ i + 1 ] ] ;
51+ yield { type : "swap" , indices : [ i + 1 , high ] , array : [ ...arr ] } ;
52+ }
53+
54+ // Mark pivot as sorted in its final position
55+ yield { type : "sorted" , index : i + 1 } ;
56+
57+ // Store pivot index for recursive calls
58+ arr . lastPivotIndex = i + 1 ;
59+ }
60+
61+ // Start the quicksort process
62+ yield * quickSortHelper ( 0 , arr . length - 1 ) ;
63+
64+ // Mark all elements as sorted
65+ yield { type : "done" , array : arr } ;
66+ }
0 commit comments