rearrange array (red, white, blue)

本文介绍了一种通过红蓝绿三种颜色标记数组元素位置的快速排序算法实现,该算法能够在O(n)的时间复杂度下完成排序,并且仅使用常数级别的额外空间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值