将数组元素分成两部分,再整体交换位置

    昨日去某公司笔试,碰到一个题如下:

    对于一个数组,已知其长度为n,和一小于n的正整数p,将该数组的前p个元素和后面的元素交换一下位置,例如a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,2,3,4,5,6},若p=6,则输出为{7,8,9,10,11,12,13,14,15},
要求占用尽可能少的空间。

    思路:其实方法很简单,将每一个元素都向前移动一位,移动P次即可,不要陷入怎么分段拷贝的思路中。

 
  
1 #include < iostream.h >
2
3   void move( int * s, int m, int n);
4
5 void main()
6 {
7 int p;
8 int arr[ 15 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 };
9 cout << " the orignal array data is: " << endl;
10 for ( int i = 0 ;i < 15 ;i ++ )
11 cout << arr[i] << " " ;
12 cout << endl;
13
14 cout << " please input a integer: " ;
15 cin >> p;
16
17 move(arr,p, sizeof (arr) / sizeof (arr[ 0 ]));
18
19 cout << " the output arry is: " << endl;
20 for (i = 0 ;i < 15 ;i ++ )
21 cout << arr[i] << " " ;
22 cout << endl;
23 }
24
25 void move( int * s, int m, int n)
26 {
27 for ( int i = 0 ;i < m;i ++ )
28 {
29 int temp = s[ 0 ];
30 for ( int j = 0 ;j < n - 1 ;j ++ )
31 s[j] = s[j + 1 ];
32 s[n - 1 ] = temp;
33
34 }
35
36 }

转载于:https://www.cnblogs.com/strider/articles/2090777.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值