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:



<think>嗯,用户的问题是关于NULL的重新排列,但不太清楚具体想要做什么。首先,我需要仔细阅读用户提供的引用内容,特别是关于NULL的定义和本质。根据引用[1],NULL在C语言中本质是0,但作为内存地址0x00000000,这可能指向零地址,而在C++中定义为0。引用[2]提到在gcc下出现段错误,这可能是因为访问了NULL指针指向的内存,而零地址通常不可访问。 用户可能遇到了使用NULL时的问题,比如程序崩溃,想了解如何正确使用或重新定义NULL。需要解释NULL的不同定义在C和C++中的区别,以及为什么解引用NULL指针会导致段错误。同时,用户可能希望了解如何安全地处理NULL,比如检查指针是否为空,避免解引用空指针,或者自定义NULL的定义。需要结合代码示例说明正确和错误的用法,并生成相关问题帮助用户深入理解。</think>### NULL的理解与使用注意事项 #### 1. NULL的本质 在C语言中,NULL的定义为$((void *)0)$,表示指向内存地址0的指针。这个地址通常不可访问,因此解引用NULL指针会导致段错误(如引用[2]中提到的gcc下段错误)[^1][^2]。例如: ```c int *p = NULL; printf("%d", *p); // 此处会触发段错误 ``` 在C++中,NULL被定义为整数0,例如: ```cpp int *p = NULL; if (p == 0) { ... } // 合法比较 ``` #### 2. 安全使用NULL的建议 - **初始化指针**:未初始化的指针可能指向随机地址,建议初始化为NULL: ```c int *p = NULL; // 明确表示p当前不指向有效内存 ``` - **检查指针有效性**:在解引用指针前必须检查: ```c if (p != NULL) { *p = 10; // 安全操作 } ``` - **避免强制转换**:C语言中不需要显式转换,但C++需要: ```cpp int *p = nullptr; // C++11起推荐使用nullptr ``` #### 3. 自定义NULL的注意事项 若需修改NULL的定义(如引用[2]中的代码),需注意: ```c #undef NULL #ifdef __cplusplus #define NULL 0 // C++环境 #else #define NULL ((void *)0) // C环境 #endif ``` 此定义确保了类型安全,但直接操作NULL指针仍可能导致未定义行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值