荷兰国旗问题

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

问题描述

简而言之,这道题就是有红白蓝三种颜色的球共n个随机排列,而我们的任务就是将这n个球按红、白、蓝顺序排好。这也就是这道题名为荷兰国旗的原因,下图即为荷兰国旗,可谓生动形象。

这道题最大的难题就在于只允许迭代一次就将数组排列好,如果没有这样的要求,这道题就很简单了,只需要一个球一个球检验就是了。

解决办法

受归并排序的启发,我认为想解决这道题,我们需要3个指针,lo、hi、current,分别代表白球的起始点分界点、终止分界点、当前位置点。答题思路就是这样:首先建立一个长度为n的数组,lo、current位于数组0位,hi位于数组n-1位。如果当前位置我们检验出颜色为红色,而且lo=current,那么就将lo、current都加1。如果当前为红色,而且lo<current那就说明,在当前这颗红球的前面已经遇到了白球,为了将红球排到前面,我们需要另lo位置的球与current位置的球互换位置,同时将lo、current都向前1位。如果检测current为白球,那么lo保持不动,current加1。如果遇到蓝球那么,我们先要将其移动到数组的后部,我们就应该交换current和hi位置的元素,同时current保持不动(因为当前current位置的球还没有检验过,是之前hi位置的球),hi要向后移动一位,即将hi-1。这样最后就能够将数组按规定排好。

整理一下:

                红=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 { 
	/* 荷兰国旗问题,有红白蓝三种小球在数组中随机排列,我们的目的是
	 * 将三种球按红白蓝三种顺序排好,而且要求只遍历数组一次 */
	public static final int red = 0;
	public static 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; // 白球的起始分界点
		int hi = n-1; // 白球的终止分界点
		int current = lo; //当前指针
		while (current <= 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) {
		// 交换两个位置的元素
		int temp = buckets[b];
		buckets[b] = buckets[a];
		buckets[a] = temp;
		
	}
	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));
		
		
	}

}

这门课我写的代码日后都会上传到我的github上:https://github.com/zhengmingzhang

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值