@@ -19,53 +19,53 @@ public class QuickSort {
19
19
* at its correct position.
20
20
*
21
21
* @param ar
22
- * @param low
23
- * @param high
22
+ * @param startIndex
23
+ * @param endIndex
24
24
* @return position of the pivot element
25
25
*/
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 ;
28
28
29
- for (int i = low ; i < high ; i ++) {
29
+ for (int i = startIndex ; i < endIndex ; i ++) {
30
30
/**
31
31
* if ith element is smaller than pivot element then
32
32
* swap it with the last larger element known
33
33
*/
34
34
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 ];
38
38
ar [i ] = temp ;
39
- low ++;
39
+ startIndex ++;
40
40
}
41
41
}
42
42
43
43
// 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 ];
46
46
ar [pivot ] = temp ;
47
47
48
- return low ;
48
+ return startIndex ;
49
49
}
50
50
51
51
/**
52
52
* 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 ).
55
55
* <p/>
56
56
* Time complexity:
57
57
* Best Case: O(nlogn)
58
58
* Worst Case: O(n*n)
59
59
*
60
60
* @param ar
61
- * @param low
62
- * @param high
61
+ * @param startIndex
62
+ * @param endIndex
63
63
*/
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 );
69
69
}
70
70
}
71
71
0 commit comments