算法学习:分治法—求最大数和次大数

 

#include <stdio.h>

 

#define MAX(a, b)         ((a)>(b) ? (a) : (b))
#define MIN(a, b)          ((a)<(b) ? (a) : (b))

#define DIM(a)                (sizeof(a)/sizeof(a[0]))
#define MINIMUM_INT32     (~0x7fffffff + 1)

 

void search_large_second(int a[], int p, int r, int *large, int *second)
{
     int q = 0;
     int left_large = 0;
     int left_second = 0;
     int right_large = 0;
     int right_second = 0;

     if (p < r)
     {
          q = (p + r) / 2;

          search_large_second(a, p, q, &left_large, &left_second);
          search_large_second(a, q+1, r, &right_large, &right_second);

          *large = MAX(left_large, right_large);
          *second = MAX(MIN(left_large, right_large), MAX(left_second, right_second));
     }
     else
     {
          *large = a[p];
          *second = MINIMUM_INT32;
     }
}

 

int main(int argc, char *argv[])
{
     int a[] = {10, 1, 12, 213, -14, 150, -160, 137, 148, 19};

     int large = 0;
     int second = 0;

     search_large_second(a, 0, DIM(a)-1, &large, &second);

     printf(“The largest number : %d/n”, large);
     printf(“The second number : %d/n”, second);

     return 0;
}

 

点赞