@@ -5,26 +5,37 @@ void swap(int* a, int* b)
55 * b = t ;
66}
77
8+ /*
9+ * Lomuto Partition Scheme:
10+ * Partitions the array so that elements < pivot are on the left,
11+ * and elements >= pivot are on the right.
12+ */
813int partition (int arr [], int low , int high )
914{
15+ // Partition the subarray around the last element as pivot and return pivot's final index.
1016 int pivot = arr [high ];
1117 int i = low - 1 ;
1218
1319 for (int j = low ; j <= high - 1 ; j ++ ) {
1420 if (arr [j ] <= pivot ) {
1521 i ++ ;
22+ // Move elements <= pivot into the left partition.
1623 swap (& arr [i ], & arr [j ]);
1724 }
1825 }
26+ // Place pivot just after the final element of the left partition.
1927 swap (& arr [i + 1 ], & arr [high ]);
2028 return i + 1 ;
2129}
2230
2331void quickSort (int arr [], int low , int high )
2432{
2533 if (low < high ) {
26- int i = partition (arr , low , high );
27- quickSort (arr , low , i - 1 );
28- quickSort (arr , i + 1 , high );
34+ /* pi is the partitioning index; arr[pi] is now at the right place */
35+ int pi = partition (arr , low , high );
36+
37+ /* Recursively sort elements before and after partition */
38+ quickSort (arr , low , pi - 1 );
39+ quickSort (arr , pi + 1 , high );
2940 }
3041}
0 commit comments