【分治法】子数组换位

Description

     
 

设a[0:n-1]是有n个元素的数组, k(0<=k<=n-1) 是一个非负整数。试设计一个算法将子数组a[0:k-1]  与 a[k:n-1] 换位。要去算法在最坏情况下耗时 O(n),且只用到O(1)的辅助空间。

 
     

Input

     
 
第一行:n k,n为a数组元素个数,k为一非负整数
第二行:a[0] a[1] ... a[n-1],a数组的n个数,以空格隔开
 
     

Output

     
 
换位之后的n个数,以空格隔开
 
     

Sample Input

     
 
5 2
1 2 3 4 5
 
     

Sample Output

     
 
3 4 5 1 2
 1 #include<iostream>  
 2 using namespace std;
 3 #define N 100
 4 int a[N];
 5 
 6 void exchange(int a[],int k,int begin,int end)
 7 {
 8     int i,j,temp;
 9     if(begin==end)//不知道为啥加了这个判断,运行速度加快了,求大神讲解
10         return;
11     if(begin+1==end)
12     {
13         temp=a[begin];
14         a[begin]=a[end];
15         a[end]=temp;
16         return;
17     }
18     if(k-begin<end-k+1)
19     {
20         for(i=k-1,j=end;i>=begin;i--,j--)
21         {
22             temp=a[i];
23             a[i]=a[j];
24             a[j]=temp;
25         }
26         end=end-(k-begin);
27         exchange(a,k,begin,end);
28     }
29     else if(k-begin>end-k+1)
30     {
31         for(i=begin,j=k;j<=end;i++,j++)
32         {
33             temp=a[i];
34             a[i]=a[j];
35             a[j]=temp;
36         }
37         begin=begin+(end-k+1);
38         exchange(a,k,begin,end);
39     }
40     else
41     {
42         for(i=begin,j=k;j<=end;i++,j++)
43         {
44             temp=a[i];
45             a[i]=a[j];
46             a[j]=temp;
47         }
48     }
49 }
50 
51 int main()  
52 {  
53     int n,k,i;
54     while(cin>>n>>k)
55     {
56         for(i=0;i<n;i++)
57             cin>>a[i];
58         exchange(a,k,0,n-1);
59         for(i=0;i<n;i++)
60             cout<<a[i]<<" ";
61         cout<<endl;
62     }
63     return 0;  
64 }  

 

 

posted @ 2014-04-23 19:46  momo_Unique  阅读(667)  评论(0编辑  收藏  举报