[代码贴]在一个数组中寻找最大值和最小值所需要进行比较的次数
数组大小为ArraySize,若ArraySize为偶数,则需要(n-2)/2×3+1次比较;若ArraySize位奇数,则需要(n-1)/2×3次比较。以两个数为一组,首先比较这两个的大小,然后分别与当前最小值和最大值比较。程序代码:
#include <stdio.h> #include <stdlib.h> #include <time.h> #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define GetMinAndMax(a, b, minimum, maximum, times) \ ({ \ unsigned int arg1 = (a); \ unsigned int arg2 = (b); \ (minimum) = MIN(arg1, arg2); \ (maximum) = MAX(arg1, arg2); \ (times)++; \ printf("time %3d: Compared %3d and %3d\n", times, arg1, arg2); \ }) #define ARRAY_SIZE 99 static int _Array[ARRAY_SIZE]; static void InitArray(void) { srand((unsigned int)time(NULL)); for(int i = 0; i < ARRAY_SIZE; i++) _Array[i] = rand() % (ARRAY_SIZE * 10); return; } static void PrintArray(void) { for(int i = 0; i < ARRAY_SIZE; i += 5) { printf("%d\t%d\t%d\t%d\t%d\n", _Array[i], _Array[i + 1], _Array[i + 2], _Array[i + 3], _Array[i + 4]); } return; } static void Findminimum(void) { unsigned int times = 0; int minimum; int maximum; int beginIndex; int tempMinimum; int tempMaximum; if(ARRAY_SIZE % 2 == 0) { GetMinAndMax(_Array[0], _Array[1], minimum, maximum, times); beginIndex = 2; } else { minimum = maximum = _Array[0]; beginIndex = 1; } for(int i = beginIndex; i < ARRAY_SIZE; i += 2) { GetMinAndMax(_Array[i], _Array[i + 1], tempMinimum, tempMaximum, times); GetMinAndMax(minimum, tempMinimum, minimum, tempMinimum, times); GetMinAndMax(tempMaximum, maximum, tempMaximum, maximum, times); } printf("Has compared %d times, and minimum is %d, maximum is %d\n", times, minimum, maximum); } int main(int argc, char * argv[]) { InitArray(); PrintArray(); Findminimum(); return EXIT_SUCCESS; }代码中GetMinAndMax宏的定义采用了gcc编译器的特性,如果在非gcc编译器上编译,很有可能出错,可以把它改写成等效的函数,在此就不该代码了。
[此贴子已经被作者于2017-7-13 17:24编辑过]