交换数组的元素! [英] Exchange an the elements of an array!

查看:161
本文介绍了交换数组的元素!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好:
我最近有一个问题.这是细节.
我得到了一个2 * N个元素的数组,像这样:array [X1,X2 ... Xn,Y1,Y2,.... Yn]
现在,我需要对数组进行排序,并将其更改为:
数组[X1,Y1,X2,Y2 ... Xn,Yn].
我写了一个像这样的函数:

Hi everyone:
I got a question recently. Here is the detail.
I got an array of 2*N elements like this:array[X1,X2...Xn,Y1,Y2,....Yn]
Now I need to sort the array and make it change to this:
array[X1,Y1,X2,Y2......Xn,Yn].
And I wrote a function like this:

   void exchange_array(char *array, int len)
{
	int index;
	char tmp_value = *(array + 1);

	char *ptr_second_half  = array + len/2;
	char *ptr_fist_half    = array + 1;
	
	while ((ptr_fist_half < ptr_second_half)&&(*ptr_fist_half != '\0'))
	{
		char tmp;
		*ptr_fist_half = *ptr_second_half;
		ptr_fist_half++;
		tmp = *ptr_fist_half;
		*ptr_fist_half = tmp_value;
		tmp_value = tmp;
		ptr_fist_half++;
		ptr_second_half++;
	}
}


数组"是我们需要处理的数组,而"len"是
的长度 数组.该功能似乎存在问题,但我无法修复.因此,有任何朋友可以给我解决此问题的方法吗?谢谢!


The "array" is the array we need to handle with,and the "len" is the length of
the array. There seems to be a problem of this function but I just can''t fix it.So can any friend give me a solution of this trouble? Thanks!

推荐答案

我会放弃就地重排,而使用第二个数组存储结果,即
I would abandon the in-place rearranging and use a second array to store the result, namely
void exchange_array(char *array, int len)
{
    assert(!(len%2)); // handle odd-sized array
    int i;
    char * res = new char [len];
    for(i=0;i<len/2;i++)
        res[2*i]=array[i];
    for (i=0; i<len/2; i++)
        res[2*i+1]=array[len/2+i];
    for (i=0; i<len;i++)
        array[i]=res[i];
    delete [] res;
}


正如我所承诺的,我指出了您的第一个错误,这是一个非常糟糕的错误.

这是循环条件下的比较!= ''\0''.首先,这不是愚蠢的以null结尾的字符串. 0值没有特殊含义.您应该使用len的值确定迭代次数,仅此而已.此外,该算法可以通用,因为无论数组元素的类型如何,它始终可以工作.没有什么需要字符类型才能工作.

一个额外的建议:如果len为奇数,则该问题没有意义.万一奇怪,我会抛出一些异常.

而已.从这一点上来说,请你一个人.

—SA
As I promised, I''m pointing out to your first mistake, which is a pretty bad one.

This is the comparison != ''\0'' in the loop condition. First of all, this is not the stupid null-terminated string. The 0 value has no special meaning. You should use the value of len to determine the number of iterations, nothing else. Besides, the algorithm can be universal, as it can always work, no matter what''s the type of the array element. There is nothing which needs character type to work.

A bonus advice: the problem makes no sense if len is odd. In case it is odd, I would simply throw some exception.

That''s it. From this point, please, you are on your own.

—SA


这篇关于交换数组的元素!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆