forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortColors.java
More file actions
57 lines (44 loc) · 1.25 KB
/
SortColors.java
File metadata and controls
57 lines (44 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package Algorithms;
import java.util.Collection;
import java.util.LinkedList;
public class SortColors {
public void sortColors(int[] A) {
int red = 0;
int curr = 0;
int blue = A.length - 1;
while(curr <= blue) {
/*
while (A[blue] == 2 && curr < blue) {
blue--;
}
while (A[red] == 0 && curr < blue) {
red ++;
}
if (red >= curr){
curr = red + 1;
}*/
if (A[curr] == 0) {
swap(A, curr, red);
curr++;
red++;
} else if (A[curr] == 1) {
curr++;
} else {
swap(A, curr, blue);
blue--;
}
}
}
public void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args){
SortColors sort = new SortColors();
int A[] = {1,0};
sort.sortColors(A);
//Collection a = new LinkedList(A);
System.out.printf("%d %d",A[0], A[1]);
}
}