@@ -19,53 +19,53 @@ public class QuickSort {
1919 * at its correct position.
2020 *
2121 * @param ar
22- * @param low
23- * @param high
22+ * @param startIndex
23+ * @param endIndex
2424 * @return position of the pivot element
2525 */
26- public static int partition (int [] ar , int low , int high ) {
27- int pivot = high , temp ;
26+ public static int partition (int [] ar , int startIndex , int endIndex ) {
27+ int pivot = endIndex , temp ;
2828
29- for (int i = low ; i < high ; i ++) {
29+ for (int i = startIndex ; i < endIndex ; i ++) {
3030 /**
3131 * if ith element is smaller than pivot element then
3232 * swap it with the last larger element known
3333 */
3434 if (ar [i ] < ar [pivot ]) {
35- // swap a[low ] with a[i]
36- temp = ar [low ];
37- ar [low ] = ar [i ];
35+ // swap a[startIndex ] with a[i]
36+ temp = ar [startIndex ];
37+ ar [startIndex ] = ar [i ];
3838 ar [i ] = temp ;
39- low ++;
39+ startIndex ++;
4040 }
4141 }
4242
4343 // place the pivot element in its correct position
44- temp = ar [low ];
45- ar [low ] = ar [pivot ];
44+ temp = ar [startIndex ];
45+ ar [startIndex ] = ar [pivot ];
4646 ar [pivot ] = temp ;
4747
48- return low ;
48+ return startIndex ;
4949 }
5050
5151 /**
5252 * Recursive Quick sort.
53- * NOTE: This function is tail-recursive (doesn't use
54- * extra stack space per recursive call ).
53+ * NOTE: This function is tail-recursive (doesn't use extra stack space per recursive call in many
54+ * programming languages but not in Java as it doesn't support tail- recursive optimization ).
5555 * <p/>
5656 * Time complexity:
5757 * Best Case: O(nlogn)
5858 * Worst Case: O(n*n)
5959 *
6060 * @param ar
61- * @param low
62- * @param high
61+ * @param startIndex
62+ * @param endIndex
6363 */
64- public static void quickSort (int [] ar , int low , int high ) {
65- if (low < high ) {
66- int partition = partition (ar , low , high );
67- quickSort (ar , low , partition - 1 );
68- quickSort (ar , partition + 1 , high );
64+ public static void quickSort (int [] ar , int startIndex , int endIndex ) {
65+ if (startIndex < endIndex ) {
66+ int partition = partition (ar , startIndex , endIndex );
67+ quickSort (ar , startIndex , partition - 1 );
68+ quickSort (ar , partition + 1 , endIndex );
6969 }
7070 }
7171
0 commit comments