用递归求数组最大值的位置(索引,下标)

用递归的思想来解决,很容易就能够想到分治的思想.

首先,定义一个函数MaxIndex()并假定它可以返回数组最值的索引(索引相对于数组开始而言,即相对开始偏移了多少.).

至少MaxIndex()是如何工作的,暂时不需要管.只需要知道,它可以返回最大值的索引不妨设为p.

因此可以将数组分为1和n-1两等份.

对后者调用MaxIndex()可得到最大值下标偏移量.

即最大值为A[p+1],相对于开始0需要多加1.用它和开始元素A[0]对比,

如果大于,则返回p+1,否则返回0即可.

 1 #include<iostream>
 2 using namespace std;
 3 int MaxIndex(int* A,int n)//时间复杂度为o(n)
 4 {
 5     if(n==1)
 6         return 0;
 7     int p=MaxIndex(A+1,n-1);
 8     return A[0]>A[p+1]? 0:p+1;
 9 }
10 
11 
12 void main()
13 {
14     int A[]={7,4,2,8,0,5};
15     int len=sizeof(A)/sizeof(A[0]);
16     int Index=MaxIndex(A,len);
17     printf("Index:%d\n".Index);18 }

 

posted on 2015-05-05 10:08  奇妙的代码之旅  阅读(2023)  评论(0编辑  收藏  举报