1 #include <iostream> 2 using namespace std; 3 4 //如何统计数组中的众数 5 //思路: 先转化为有序数组 6 // 再来查找众数 7 void sortMethod(int intArray[],int array_size); 8 void printMethod(int intArray[],int array_size); 9 int zhongshuMethod(int intArray[],int array_size); 10 int main() 11 { 12 const int array_size = 15; 13 int age[] = {30,10,20,50,40,40,40,40,30,10,2,2,2,2,2}; 14 sortMethod(age,array_size); 15 printMethod(age,array_size); 16 17 int result = zhongshuMethod(age,array_size); 18 cout << "result: " << result << endl; 19 20 return 0; 21 } 22 void sortMethod(int intArray[],int array_size) 23 { 24 for(int i=0; i<array_size-1; i++) 25 { 26 for(int j=i+1; j<array_size; j++) 27 { 28 if(intArray[i] > intArray[j]) 29 { 30 int temp; 31 temp = intArray[i]; 32 intArray[i] = intArray[j]; 33 intArray[j] = temp; 34 } 35 } 36 } 37 } 38 int zhongshuMethod(int intArray[],int array_size) 39 { 40 int zhongshu; 41 int currentFrequency = 0; 42 int mostFrequency = 0; 43 for(int i=0; i<array_size; i++) 44 { 45 currentFrequency++; 46 if(intArray[i] != intArray[i+1] || i == array_size-1) 47 { 48 if(currentFrequency > mostFrequency) 49 { 50 mostFrequency = currentFrequency; 51 zhongshu = intArray[i]; 52 } 53 currentFrequency = 0; 54 } 55 } 56 return zhongshu; 57 } 58 void printMethod(int intArray[],int array_size) 59 { 60 for(int i=0; i<array_size; i++) 61 { 62 cout << intArray[i] << " "; 63 } 64 cout << endl; 65 }
原文地址:https://www.cnblogs.com/littlelittleprince/p/10663119.html
时间: 2024-10-18 04:14:09