Dutch flag problem __ Dutch flag problem

Source: Internet
Author: User

There is an array, the length of N, which is only 0, 1, 2 (respectively for red, white, blue), now requires the way through 22 exchanges, so that 0 in the front, 1 in the middle, 2 in the last.

The code implementation is as follows:

Package com.threeTop.www;

/**
 * Dutch flag issue
 * @author WJGS * */Public
class Dutchflag {
     
	/**
	 * Dutch flag issue
	 * @param array< c9/>*/public
	static void sort (int []array)
	{
		int begin=0;
		int end=array.length-1;
		int current=0;
		while (Current<=end)
		{
			if (array[current]==0)
			{
				swap (array,current,begin);
				begin++;
				current++;
			}
			else if (array[current]==1)
			{
				current++
			} else if (array[current]==2)
			{
				swap (array,current,end);
				end--
			}
		}
		System.out.print ("sorted result:");
		
		for (int i=0;i<array.length;i++)
		{
			System.out.print (array[i]+ ",");
		}
	}
	Swap two elements
	private static void Swap (int[] array, int x, int y)
	{
		int temp=array[x];
		 Array[x]=array[y];
		 array[y]=temp;
		
	}
	public static void Main (string[] args) 
	{
		 int []array={1,1,0,0,2,2,1,0,1,2,1,0,2};
		 int []array2={1,1,0,0,2,2,1,0,1,2,1,0,2};
		 Dutchflag.sort (array);
		 System.out.println ();
		 Dutchflag.sort (array2);
	}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.