¶þ·Ö²éÕÒËã·¨ÊÇÔÚÓÐÐòÊý×éÖÐÓõ½µÄ½ÏΪƵ·±µÄÒ»ÖÖËã·¨£¬ÔÚδ½Ó´¥¶þ·Ö²éÕÒË㷨ʱ£¬×îͨÓõÄÒ»ÖÖ×ö·¨ÊÇ£¬¶ÔÊý×é½øÐбéÀú£¬¸úÿ¸öÔªËؽøÐбȽϣ¬Æäʱ¼äΪO(n).µ«¶þ·Ö²éÕÒËã·¨Ôò¸üÓÅ£¬ÒòΪÆä²éÕÒʱ¼äΪO(lgn)£¬Æ©ÈçÊý×é{1£¬ 2£¬ 3£¬ 4£¬ 5£¬ 6£¬ 7£¬ 8£¬ 9}£¬²éÕÒÔªËØ6£¬Óöþ·Ö²éÕÒµÄËã·¨Ö´ÐеĻ°£¬Æä˳ÐòΪ£º
1. µÚÒ»²½²éÕÒÖмäÔªËØ£¬¼´5£¬ÓÉÓÚ5<6£¬Ôò6±ØÈ»ÔÚ5Ö®ºóµÄÊý×éÔªËØÖУ¬ÄÇô¾ÍÔÚ{6£¬ 7£¬ 8£¬ 9}ÖвéÕÒ¡£
2. Ñ°ÕÒ{6£¬ 7£¬ 8£¬ 9}µÄÖÐλÊý£¬Îª7£¬7>6£¬Ôò6Ó¦¸ÃÔÚ7×ó±ßµÄÊý×éÔªËØÖУ¬ÄÇôֻʣÏÂ6£¬¼´ÕÒµ½ÁË¡£
3. ¶þ·Ö²éÕÒËã·¨¾ÍÊDz»¶Ï½«Êý×é½øÐж԰ë·Ö¸î£¬Ã¿´ÎÄÃÖмäÔªËغÍgoal½øÐбȽϡ£
×¢Ò⣺±ØÐëÊÇÒ»×éÅÅÁÐÓÐÐòµÄÊýÖµ¡£?xml:namespace>
¾ßÌåʵÏÖ¹ý³Ì£º
#include <stdio.h>
void search(int *a,int num,int n); int main() { int a[] = {10 ,4,5,60,90,100,3,55}; int n = sizeof(a)/sizeof(int); int i,j; for(i = 0;i<n-1;i++) { for(j = 0;j<n-1-i;j++) { if(a[j]>a[j+1]) { int tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } } } for(i = 0;i<n;i++) { printf("%4d",a[i]); } printf("\n"); int num; while(1) { printf("ÇëÊäÈëÄãÒª²éÕÒµÄÊý×Ö£º\n"); scanf("%d",&num); search(a,num,n); }
return 0; }
void search(int *a,int num,int n) { int left = 0; int right = n-1; int mid = (left + right)/2;
while(a[mid] != num &&left < right) { if(a[mid]>num) { right = mid -1; } else if (a[mid] < num) { left = mid + 1; } mid = (left + right)/2; } if(a[mid] == num) { printf("²éÕÒºóµÄÖµ£º%d\n",a[mid]); } else { printf("²éÕÒ²»µ½\n"); }
} |