看萌芽网上一道题,正好有时间就写写。平常都用2分法找最大数,这个第2大。我用最朴实的冒泡法写出了这个算法,等有时间了用2分法写下,效率能比这个高不少。直接贴代码了。
#include <iostream> using namespace std; int GetSecondMaxNum(int *pArray, size_t length) { if(length == 1) { return 0; } else if(length == 2) { int temp = *pArray; return temp < *(++pArray) ? temp : (*pArray); } int nTempFront = *pArray; int nTemp = *(++pArray); if(nTempFront > nTemp) { nTemp = nTempFront; nTempFront = *pArray; } pArray++; for(size_t i = 2; i < length; ++i, ++pArray) { if(*pArray > nTemp) { nTempFront = nTemp; nTemp = *pArray; } else if((*pArray > nTempFront) &&(*pArray < nTemp)) { nTempFront = *pArray; } } return nTempFront; } int main() { int array[] ={2,1,24,26,25,98,0,22,32,15,44,15,56,78,14}; cout<<GetSecondMaxNum(array, sizeof(array)/4)<<endl;