版权声明:copyright@Leon_CSDN https://blog.csdn.net/LeonSUST/article/details/88060648
Before
是在网上看到的 很好的程序 我后面还做了小修改 节约了行数 减少了变量
让我们往下看
用递归的思想来解决,很容易就能够想到分治的思想.
首先,定义一个函数 MaxIndex() 并假定它可以返回数组最值的索引(索引相对于数组开始而言,即相对开始偏移了多少
至少 MaxIndex() 是如何工作的,暂时不需要管.只需要知道,它可以返回最大值的索引不妨设为p.
因此可以将数组分为1和n-1两等份.
对后者调用 MaxIndex() 可得到最大值下标偏移量.
即最大值为A[p+1],相对于开始0需要多加1.用它和开始元素A[0]对比,
如果大于,则返回p+1,否则返回0即可.
c++版
#include<iostream>
using namespace std;
int MaxIndex(int* A,int n)//时间复杂度为o(n)
{
if(n==1)
return 0;
int p=MaxIndex(A+1,n-1);
return A[0]>A[p+1]? 0:p+1;
}
void main()
{
int A[]={7,4,2,8,0,5};
int len=sizeof(A)/sizeof(A[0]);
int Index=MaxIndex(A,len);
printf("Index:%d\n".Index);
}
后面的主程序进行简化 直接出结果 这样写:
c版
#include "stdio.h"
/**
* [MaxIndex 递归返回数组最大值索引]
* @param A [数组]
* @param n [数组长度]
* @return [最大值索引]
*/
int MaxIndex(int* A, int n) //时间复杂度为o(n)
{
if (n == 1)
return 0;
int p = MaxIndex(A + 1, n - 1);
return A[0] > A[p + 1] ? 0 : p + 1;
}
int main(void)
{
int A[] = {7, 4, 2, 8, 0, 5};
printf("Index:%d\n", MaxIndex(A, sizeof(A) / sizeof(A[0])));
}