数列切断倒置程序

根据Bently写的<<编程珠玑>>(programming pearls)写的一个例程,解决的问题可以简要概述为:

[A, B]-->[B, A]例如:
输入[1, 2, 3, 4, 5], 切断位置(partitioning position)为2,那么输出为:
[3, 4, 5, 1, 2]。
问题看似简单,大家千万别小看它的编程难度, 我对编程水平的理解,应该是程序时间(多快的运算时间),空间(多省的内存占用量)以及代码长度(多言简意赅的代码)这三者的综合。
下面代码的编程思想,我可以借用线性代数里面的一个公式概括出来:
(A'B')' = (BA)
just for fun! For more information, please refer to Bentley's book <programming pearls>
place exchange program:
#include <iostream>
#include <assert.h>
using namespace std;
template <class Type>
void exchange_place(const Type *pArr, const int Arr_len, int pos,
Type **ppArr_out)
//Effect: pArr [A, B] --> (*ppArr_out)[B, A], with the cutting position 'pos'
//Inputs:
//pArr: the input array
//Arr_len: the length of the input Array
//pos: the partitioning position
//Outputs:
//*ppArr_out: [B, A]
//Author: Su Dongcai at 2011/12/11
//Key ideal:
//(A'B')' = (BA)
{
(*ppArr_out) = new Type[Arr_len];
memcpy(*ppArr_out, pArr, Arr_len*sizeof(Type));
assert(pos < Arr_len);
//A'
reverse(*ppArr_out, pos);
//B'
reverse((*ppArr_out)+pos, Arr_len-pos);
//(A'B')'
reverse(*ppArr_out, Arr_len);
}
template <class Type>
void reverse(Type *pArr, const int Arr_len)
//Effect: reverse the input array: pArr [a, b] --> pArr[b, a]
//inputs:
//pArr: the input array
//Arr_len: the length of input array
//outputs:
//pArr: the reversed Array
//Author: Su Dongcai at 2011/12/11
{
assert(Arr_len > 0);
Type *pArr_cp = new Type[Arr_len];
memcpy(pArr_cp, pArr, Arr_len*sizeof(Type));
//now we reverse:
int i;
for(i=0; i<Arr_len; i++)
{
pArr = pArr_cp[Arr_len-i-1];
}
delete [] pArr_cp;
}
template <class Type>
void display(Type *pArr, const int Arr_len)
{
cout<<"[";
int i;
for(i=0; i<Arr_len; i++)
{
cout<<pArr<<", ";
}
cout<<"]"<<endl;
}
//main entrance for test purpose:
int main(int argc, char *argv[])
{
int Array[] = {1, 2, 3, 4, 5};
int *pArr;
exchange_place<int>(Array, 5, 2, &pArr);
display<int>(pArr, 5);
delete [] pArr;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值