two methods for calculating the maximum (minimum) value of an array1, the common method (for the maximum value for example)
1#include"stdafx.h"2#include <string>3 using namespacestd;4 int_tmain (intARGC, _tchar*argv[])5 {6 inta[5] = {1, at,2,6,7 };7 intArray_length =sizeof(a)/sizeof(a[0]);//Array Size8 intmax=a[0];9 for(inti =1; i < array_length; i++)Ten { One if(a[i]>max) A { -Max =A[i]; - } the } -printf"the maximum value for array A is%d", max); - GetChar (); - return 0; +}2. Search for maximum and minimum values simultaneously
One way of thinking is that the above-mentioned common search maximum and minimum algorithm run once can be the maximum and minimum value to find out, so in the case of the worst input situation, the algorithm run time complexity of O (2n). Another way of thinking is to compare the number of consecutive two numbers in the array, take the larger and the temporary maximum value for comparison, take the smallest and temporary minimum value for comparison, until the last iteration of the array is completed, you can get the maximum value of the minimum value. In the worst case, the time complexity of this algorithm is O (3[N/2]) ([N/2] represents down rounding), the algorithm is implemented as follows:
1#include"stdafx.h"2#include <string>3 using namespacestd;4 int_tmain (intARGC, _tchar*argv[])5 {6 inta[9] = {3,2,6,1,7,Ten, -,9, -};7 intArray_length =sizeof(a)/sizeof(a[0]);//Array Size8 intmax=-10000;//Temporary Maximum value9 intmin=10000;//Temporary Minimum valueTen for(inti =0; I < array_length && i+1<array_length; i=i+2) One { A if(A[i] < A[i +1]) - { - if(A[i] <min) the { -Min =A[i]; - } - if(A[i +1]>max) + { -max = A[i +1]; + } A}Else{ at if(a[i+1] <min) - { -Min = a[i+1]; - } - if(a[i]>max) - { inMax =A[i]; - } to } + } - //if the size of the array is the base, the last value in the set will be taken out alone to make a judgment . the if(Array_length%2!=0) * { $ if(A[array_length-1] <min)Panax Notoginseng { -Min = a[array_length-1]; the } + if(A[array_length-1] >max) A { themax = A[array_length-1]; + } - } $printf"the maximum value for array A is%d and the minimum value is%d", Max, min); $ GetChar (); - return 0; -}3, look for an array of the small number I
The idea is actually very simple, the array does a non-descending sort, and then find the number of the first order in the sequence can be. The relevant contents of the sorting algorithm can be viewed in this blog post of the author.
Two methods for calculating the maximum (minimum) value of an array