Cousera Algorithms
PartI第二周课后问答题，有这样一道题，当时没什么想法，直到学了第三周的归并排序，才弄明白要怎么做，这里记录一下自己的想法与最终代码。

红=1

白=0

蓝=2

if （color(current)==1 && less(lo,current) )

swap(lo,current); // 互换位置

lo++;

current++;

else if (color(currrent)==1 && color(lo)==1)

lo++;

current++;

else if(color(current)==0)

current++;

else if (color(current)==2)

swap(current,hi);

hi--;

import java.util.Arrays; import edu.princeton.cs.algs4.StdRandom; public class
DutchNationalFlag { /* 荷兰国旗问题，有红白蓝三种小球在数组中随机排列，我们的目的是 *

final int white = 1; public static final int blue = 2; private int n; private
int[] buckets; public DutchNationalFlag (int[] buckets) { // 创建一个数组 n =
buckets.length; this.buckets = buckets; } public void sort() { int lo = 0; //

hi) { switch(color(current)) { case red: if (current != lo) swap (current ,
lo); current ++; lo ++; break; case white: current ++; break; case blue: swap
(current , hi); hi--; break; } } } private void swap(int a, int b) { //

private int color(int c) { // 检测当前位置的颜色 return buckets[c]; } public static void
main(String[] args) { int n = 10; int [] buckets = new int[n]; for (int i = 0;
i < n; i++) { buckets[i] = StdRandom.uniform(3); } DutchNationalFlag s = new
DutchNationalFlag (buckets); System.out .println(Arrays.toString(buckets));
s.sort(); System.out .println(Arrays.toString(buckets)); } }

<https://github.com/zhengmingzhang>

30天阅读排行