1+ /**
2+ * Quick Sort Implementation
3+ *
4+ * 📌 Concept:
5+ * Quick Sort follows Divide and Conquer:
6+ * 1. Choose a pivot element
7+ * 2. Place pivot at its correct sorted position
8+ * 3. Elements smaller than pivot go left
9+ * 4. Elements greater than pivot go right
10+ * 5. Recursively sort left and right subarrays
11+ *
12+ * 📊 Time Complexity:
13+ * Best Case : O(n log n)
14+ * Average Case: O(n log n)
15+ * Worst Case : O(n^2)
16+ *
17+ * 📦 Space Complexity:
18+ * O(log n) due to recursion stack
19+ *
20+ * ⚠️ Quick Sort is NOT stable
21+ */
22+ public class QuickSort {
23+
24+ public static void main (String [] args ) {
25+
26+ int [] arr = {10 , 7 , 8 , 9 , 1 , 5 };
27+
28+ System .out .println ("Before Sorting:" );
29+ printArray (arr );
30+
31+ quickSort (arr , 0 , arr .length - 1 );
32+
33+ System .out .println ("After Sorting:" );
34+ printArray (arr );
35+ }
36+
37+ /**
38+ * Recursive Quick Sort function
39+ */
40+ public static void quickSort (int [] arr , int low , int high ) {
41+
42+ // Base condition
43+ if (low < high ) {
44+
45+ // Partition array and get pivot index
46+ int pivotIndex = partition (arr , low , high );
47+
48+ // Sort left subarray
49+ quickSort (arr , low , pivotIndex - 1 );
50+
51+ // Sort right subarray
52+ quickSort (arr , pivotIndex + 1 , high );
53+ }
54+ }
55+
56+ /**
57+ * Partitions array around pivot
58+ *
59+ * Pivot chosen: last element
60+ *
61+ * After partition:
62+ * - smaller elements on left
63+ * - greater elements on right
64+ */
65+ private static int partition (int [] arr , int low , int high ) {
66+
67+ int pivot = arr [high ];
68+
69+ int i = low - 1 ;
70+
71+ for (int j = low ; j < high ; j ++) {
72+
73+ // Place smaller elements before pivot
74+ if (arr [j ] <= pivot ) {
75+
76+ i ++;
77+
78+ swap (arr , i , j );
79+ }
80+ }
81+
82+ // Place pivot in correct position
83+ swap (arr , i + 1 , high );
84+
85+ return i + 1 ;
86+ }
87+
88+ /**
89+ * Utility method to swap two elements
90+ */
91+ private static void swap (int [] arr , int i , int j ) {
92+
93+ int temp = arr [i ];
94+ arr [i ] = arr [j ];
95+ arr [j ] = temp ;
96+ }
97+
98+ /**
99+ * Utility method to print array
100+ */
101+ private static void printArray (int [] arr ) {
102+
103+ for (int num : arr ) {
104+ System .out .print (num + " " );
105+ }
106+
107+ System .out .println ();
108+ }
109+ }
110+
111+ /**
112+ * ⚠️ Worst Case in Quick Sort
113+ *
114+ * Worst case occurs when pivot selection creates highly unbalanced partitions.
115+ *
116+ * Example:
117+ * - Already sorted array
118+ * - Reverse sorted array
119+ *
120+ * If smallest or largest element is always chosen as pivot:
121+ * Time Complexity becomes O(n^2)
122+ *
123+ * 💡 Optimization Techniques:
124+ * - Random Pivot
125+ * - Median of Three
126+ */
0 commit comments