rearrange array (red, white, blue)

1.Description

Suppose an array  A  consists of  n  elements, each of which is red, white, or blue. We seek to rearrange the elements so that all the reds come before all the whites, which come before all the blues. Your algorithm should run in  O(n)  time in the worst case using  O(1)  space.

2.Algorithm

Partition the array using Red as pivot. When done, all the red element will be at the beginning of the array.

Partition the remaining array, from the last Red element until the end, using Blue as pivot. Done.

3.Implementation

import java.util.Arrays;
public class HW2 {
	public static void rearrange(String a[])
	{
		int i=0,n=a.length,j=n-1;
		while(i<j)
		{
			while(i<n&&a[i]=="red") i++;
			while(j>=0&&a[j]!="red") j--;
			if(i<j) swap(a,i,j);
		}
		j=n-1;
		while(i<j)
		{
			while(i<n&&a[i]=="white") i++;
			while(j>=0&&a[j]!="white")	j--;
			if(i<j) swap(a,i,j);
		}
	}
	//exchange two elements in the array
	public static void swap(String a[] ,int i,int j)
	{
		String temp=a[i];
		a[i]=a[j];
		a[j]=temp;	
	}
	public static void main(String[] args){
		String seq[] = {"blue", "white","red", "blue", "blue", "red", "red", "white", "red","white"};
		rearrange(seq);
		System.out.println(Arrays.toString(seq));
	}
}

Screenshot of the result:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值