File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ class Solution {
3
+ public:
4
+ void sortColors (int A[], int n) {
5
+ // Start typing your C/C++ solution below
6
+ // DO NOT write int main() function
7
+
8
+ int low = 0 , high = n - 1 ;
9
+ int mid = 0 ;
10
+
11
+ while (mid <= high) {
12
+ if (A[mid] == 0 ) {
13
+ A[mid++] = A[low];
14
+ A[low++] = 0 ;
15
+ }
16
+ else if (A[mid] == 1 ) {
17
+ mid += 1 ;
18
+ }
19
+ else if (A[mid] == 2 ) {
20
+ A[mid] = A[high];
21
+ A[high--] = 2 ;
22
+ }
23
+ }
24
+ }
25
+ };
26
+
27
+ //
28
+ // Solution2 using the method like quicksort
29
+ //
30
+ class Solution2 {
31
+ public:
32
+ void sortColors (int A[], int n) {
33
+ // Start typing your C/C++ solution below
34
+ // DO NOT write int main() function
35
+
36
+ int p = split (A, 0 , n - 1 , 0 );
37
+ split (A, p + 1 , n - 1 , 1 );
38
+ }
39
+ int split (int A[], int low, int high, int pivot) {
40
+ int i = low - 1 ;
41
+ for (int j = low; j <= high; j++) {
42
+ if (A[j] <= pivot) {
43
+ i += 1 ;
44
+ if (i != j) swap (A[i], A[j]);
45
+ }
46
+ }
47
+ return i;
48
+ }
49
+ };
You can’t perform that action at this time.
0 commit comments