public class HollandFlagProblem {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A = { 2, 0, 2, 0, 0, 2, 1, 1, 0, 2, 1, 0, 1, 2, 0, 1, 2, 0, 1, 0,
2, 1, 0, 2, 0, 1, 2, 0, 1, 2, 0, 2, 1, 0 };
// 排序前
for (int i : A) {
System.out.print(i + " ");
}
sort(A);
// 排序后
for (int i : A) {
System.out.print(i + " ");
}
}
public static void sort(int[] arr) {
int cur = 0;
int start = 0;
int end = arr.length - 1;
while (cur <= end) {
if (arr[cur] == 0) {
swap(arr, cur, start);
start++;
cur++;
} else if (arr[cur] == 2) {
swap(arr, cur, end);
end--;
} else {
cur++;
}
}
}
public static void swap(int[] a, int p, int q) {
int temp = a[p];
a[p] = a[q];
a[q] = temp;
}
}
荷兰国旗问题java
最新推荐文章于 2023-02-23 21:10:59 发布