您的位置:首页 > 其它

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

2013-06-22 19:47 756 查看
题目描述:将数组里的负数排在数组的前面,正数排在数组的后面。但不改变原先负数和正数的排列顺序。例: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐