1+ //Q. how to implement quicksort in java?
2+
3+
4+
15class QuickSort {
26 //main method
37 public static void main (String args []) {
4- int arr [] = { 101 , 37 , 68 , 29 , 11 , 5 };
8+ int arr [] = { 101 , 37 , 68 , 29 , 11 , 5 }; //takingthe input array
59 System .out .println ("before sorting array" );
610 for (int element : arr ) {
7- System .out .print (element + " " );
11+ System .out .print (element + " " ); // input = 101, 37, 68, 29, 11, 5
812 }
913 System .out .println ();
10- int n = arr .length ;
14+ int n = arr .length ; // 6
1115 QuickSort ob = new QuickSort ();
12- ob .sort (arr , 0 , n - 1 );
16+ ob .sort (arr , 0 , n - 1 ); // here we call the sort method for sorting the array
1317
1418 System .out .println ("after sorting array" );
15- printArray (arr );
19+ printArray (arr ); // after performing sort method now we are going to print the sorted array
1620 }
1721
1822 // Partition Method
@@ -36,16 +40,16 @@ int partition(int arr[], int lowIndex, int highIndex) {
3640 void sort (int arr [], int lowIndex , int highIndex ) {
3741 if (lowIndex < highIndex ) {
3842 int pi = partition (arr , lowIndex , highIndex );
39- sort (arr , lowIndex , pi - 1 );
40- sort (arr , pi + 1 , highIndex );
43+ sort (arr , lowIndex , pi - 1 ); //left array of pivot
44+ sort (arr , pi + 1 , highIndex ); //right array of pivot
4145 }
4246 }
4347// method to print array
4448 static void printArray (int arr []) {
4549 int n = arr .length ;
4650
4751 for (int i = 0 ; i < n ; ++i )
48- System .out .print (arr [i ] + " " );
52+ System .out .print (arr [i ] + " " ); // output = 5 11 29 37 68 101
4953 System .out .println ();
5054 }
5155}
0 commit comments