将数组里的负数排在数组的前面,正数排在数组的后面。但不改变原先负数和正数的排列顺序。

题目描述:将数组里的负数排在数组的前面,正数排在数组的后面。但不改变原先负数和正数的排列顺序。例:input: -5,2,-3, 4,-8,-9, 1, 3,-10;output: -5, -3, -8, -9, -10, 2, 4, 1, 3。

算法描述:

①设定两个计数器begin、end,其中begin始终指向数组中的第一个负数,end始终指向位于begin之后的第一个正数。然后把begin、end之间的数字往后移,即让原来end位置的数字移动到begin位置,循环上述过程。直到end大于数组长度即break。

②设两个指针positive, negative,初始指向数组最后一个元素,然后从后往前遍历数组,positive每次指向第一个满足positive<negative的正数,negative指向最后一个负数,然后将positive+1到negative的元素往前移,将positive移至negative位置。循环上述过程,直至positive<0时。

#include <stdio.h>

/*
* Author : Tian Mo
*
* Date   : 2013-06-22 19:37
*
* Locate : Baidu PS, Beijing
*/

int SepPositiveNegative(int *v, const unsigned int len)
{
	/* ASSERT ERROR */
	if (NULL == v || len <= 0)
	{
		return -1;
	}

	int i,j,k,begin,end,temp;

	for(i = 0; i < len; ++ i)
	{
		/* From current data start compute */
		k = i;
		while(v[k] >= 0)
		{
			++ k;
		}
		/* Record the first negative always */
		begin = k;
	
		while(v[k] < 0)
		{
			++ k;
		}
		/* Record the first positive which after the first negative always */
		end = k;

		/* if the last negative beyond the length of array v, must be break */
		if (end > len - 1)
		{
			break;
		}
		
		/* Move the first positive which after the first negative to		\
		   the place where the first negative begin  */
		temp = v[end];
		for(j = end; j > begin; -- j)
		{
			v[j] = v[j - 1];
		}
		v[begin] = temp;		
	}
	
	return 0;
}

void print(const int *v, const unsigned int len)
{
	printf("Items AS : ");
	unsigned int i;
	for (i = 0; i < len; ++ i)
	{
		printf("%2d ", v[i]);
	}
	printf("\n");
}

int main()
{
	int v[] = {-5, 2, -3, 4, -8, -9, 1, 3, -10};
	//int v[] = {-5, 2, -3, 4, -8, -9, 1, 3, 12, 15, 19, -7,-2,};
	//int v[] = {-1, -3, -5, -7, 1, 3, 5, 7, 9};
	const len = sizeof(v) / sizeof(v[0]);

	print(v, len);

	if (-1 != SepPositiveNegative(v, len))
	{
		print(v, len);
	}
	else 
	{
		printf("Compute Data Error.\n");
	}
	
	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值