Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commiteeaf7d0

Browse files
committed
sort
1 parent6486347 commiteeaf7d0

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

‎sort/SortColors.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
packageAlgorithms.sort;
2+
3+
publicclassSortColors {
4+
publicvoidsortColors(int[]A) {
5+
if (A ==null ||A.length ==0) {
6+
return;
7+
}
8+
9+
intlen =A.length;
10+
11+
intred =0;
12+
intwhite =0;
13+
14+
for (inti =0;i <len;i++) {
15+
if (A[i] ==0) {
16+
red++;
17+
}elseif (A[i] ==1) {
18+
white++;
19+
}
20+
}
21+
22+
for (inti =0;i <len;i++) {
23+
if (red >0) {
24+
A[i] =0;
25+
red--;
26+
}elseif (white >0) {
27+
A[i] =1;
28+
white--;
29+
}else {
30+
A[i] =2;
31+
}
32+
}
33+
}
34+
35+
publicvoidsortColors2(int[]A) {
36+
if (A ==null ||A.length ==0) {
37+
return;
38+
}
39+
40+
intlen =A.length -1;
41+
intleft =0;
42+
intright =len;
43+
44+
intcur =0;
45+
while (cur <=right) {
46+
if (A[cur] ==2) {
47+
// 换到右边,换过来的有可能是0,也有可能是1,所以cur要停留
48+
49+
swap(A,cur,right);
50+
right--;
51+
}elseif (A[cur] ==0) {
52+
// 从左边换过来的只可能是1,所以可以直接cur++
53+
// 因为所有的2全部换到右边去了。
54+
55+
swap(A,cur,left);
56+
left++;
57+
cur++;
58+
}else {
59+
cur++;
60+
}
61+
}
62+
}
63+
64+
publicvoidswap(int[]A,intn1,intn2) {
65+
inttmp =A[n1];
66+
A[n1] =A[n2];
67+
A[n2] =tmp;
68+
}
69+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp