1
1
package com .hackerrank .algorithms .arraysandsorting ;
2
2
3
- import java .util .ArrayList ;
4
- import java .util .List ;
5
3
import java .util .Scanner ;
6
4
7
5
/**
13
11
*/
14
12
public class QuickSort2 {
15
13
16
- static void quickSort (int [] ar , int start , int end ) {
17
- int pivot = ar [0 ];
18
- List <Integer > ar1 = new ArrayList <>();
19
- List <Integer > ar2 = new ArrayList <>();
20
-
21
- for (int i = start ; i < end ; i ++) {
22
- if (ar [i ] < pivot ) {
23
- ar1 .add (ar [i ]);
24
- } else if (ar [i ] > pivot ) {
25
- ar2 .add (ar [i ]);
14
+ static int partition (int [] a , int start , int end ) {
15
+
16
+ int pivot = start , temp ;
17
+
18
+ for (int i = start + 1 ; i <= end ; i ++) {
19
+ // maintains the relative positioning of elements in each partition
20
+ if (a [i ] < a [pivot ]) {
21
+ start ++;
22
+ temp = a [i ];
23
+ int j ;
24
+ for (j = i ; j > start ; j --) {
25
+ a [j ] = a [j - 1 ];
26
+ }
27
+ a [j ] = temp ;
26
28
}
27
29
}
28
30
29
- //TODO
31
+ temp = a [pivot ];
32
+ while (pivot < start ) {
33
+ a [pivot ] = a [pivot + 1 ];
34
+ pivot ++;
35
+ }
36
+ a [pivot ] = temp ;
37
+
38
+ return pivot ;
30
39
}
31
40
32
- static void printArray (int [] ar ) {
33
- for (int n : ar ) {
34
- System .out .print (n + " " );
41
+ static void quickSort (int [] ar , int start , int end ) {
42
+ if (start < end ) {
43
+ int p = partition (ar , start , end );
44
+ quickSort (ar , start , p - 1 );
45
+ quickSort (ar , p + 1 , end );
46
+ for (int i = start ; i <= end ; i ++) {
47
+ System .out .print (ar [i ] + " " );
48
+ }
49
+ System .out .println ();
35
50
}
36
- System .out .println ("" );
37
51
}
38
52
39
53
public static void main (String [] args ) {
@@ -43,6 +57,6 @@ public static void main(String[] args) {
43
57
for (int i = 0 ; i < n ; i ++) {
44
58
ar [i ] = in .nextInt ();
45
59
}
46
- quickSort (ar , 0 , ar . length );
60
+ quickSort (ar , 0 , n - 1 );
47
61
}
48
62
}
0 commit comments