Optimization of the number of comparisons between the maximum and minimum values of the array

      The number of comparisons of the algorithm for finding the maximum and minimum values ​​of the array is O(2n), because both max and min need to compare the array with each element in it. The following describes the O(1.5n) method, first look at the code:

#include <stdio.h>

//求数组的最大值和最小值,要求比较次数的数量级是O(1.5n)
void getMinMax(int a[],int n){
	int max=0,min=0;

	for(int i=0;i<n;i++){
		if(i+1 < n){
			if(a[i] < a[i+1]){
				if(min > a[i]){
					min = a[i];
				}	

				if(max < a[i+1]){
					max = a[i+1];
				}
				
			}else{
				if(min > a[i+1]){
					min = a[i];
				}

				if(max < a[i]){
					max = a[i+1];
				}
			}
			
		}else{
				if(min > a[i]){
					min = a[i];
				}

				if(max < a[i]){
					max = a[i];
				}
			}
		
	}

	printf("%d,%d\n",max,min);
}


int main(){

	int a[8] = {3,7,4,1,5,9,6,-2};
	getMinMax(a,8);

	return 0;
}

     The number of comparisons is O(1.5n), because when comparing 4,1, first compare 4,1, and then compare with max and min, which compares 3 times. It is common that both max and min will be compared with 4,1, so the number of times is 4.

     

Guess you like

Origin blog.csdn.net/ma2595162349/article/details/108568943