1 /**************************************** 2 > File Name:test.c 3 > Author:xiaoxiaohui 4 > mail:[email protected] 5 > Created Time:2016年05月23日 星期一 20时07分13秒 6 ****************************************/ 7 8 9 10 /*这是典型的类二分查找算法,只要找到分间线,就是其中最下的元素*/ 11 12 #include<stdio.h> 13 14 int min(int *buf, int length) 15 { 16 if(buf == NULL || length <= 0) 17 { 18 printf("parameter is error!\n"); 19 return -1; 20 } 21 22 int left = 0; 23 int right = length - 1; 24 int mid = 0; 25 26 while(right > left) 27 { 28 if( (right - left) == 1) 29 { 30 break; 31 } 32 33 mid = left + (right - left) / 2; 34 if(buf[mid] >= buf[left]) 35 { 36 left = mid; 37 } 38 else if(buf[mid] <= buf[right]) 39 { 40 right = mid; 41 } 42 } 43 44 return buf[right]; 45 }
1 /**************************************** 2 > File Name:test.c 3 > Author:xiaoxiaohui 4 > mail:[email protected] 5 > Created Time:2016年05月23日 星期一 20时07分13秒 6 ****************************************/ 7 8 9 10 /*这是典型的类二分查找算法,只要找到分间线,就是其中最下的元素*/ 11 12 #include<stdio.h> 13 14 int min(int *buf, int length) 15 { 16 if(buf == NULL || length <= 0) 17 { 18 printf("parameter is error!\n"); 19 return -1; 20 } 21 22 int left = 0; 23 int right = length - 1; 24 int mid = 0; 25 26 while(right > left) 27 { 28 if( (right - left) == 1) 29 { 30 break; 31 } 32 33 mid = left + (right - left) / 2; 34 35 if(buf[right] == buf[left] && buf[left] == buf[mid]) //顺序查找 36 { 37 for(int i = left; i <= right; i++) 38 { 39 if(buf[left] > buf[i]) 40 { 41 return buf[i]; 42 } 43 } 44 } 45 46 if(buf[mid] >= buf[left]) 47 { 48 left = mid; 49 } 50 else if(buf[mid] <= buf[right]) 51 { 52 right = mid; 53 } 54 } 55 56 return buf[right]; 57 }
时间: 2024-10-06 21:44:42