C/C++:各種基本演算法實現小結(六)—— 查詢演算法
阿新 • • 發佈:2019-01-04
各種基本演算法實現小結(六)—— 查詢演算法
(均已測試通過)
===================================================================
1、簡單查詢
在一組無序數列中,查詢特定某個數值,並返回其位置pos
測試環境:VC 6.0 (C)
[cpp] view plain copy print?- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define MAX 101
-
void input(int num[])
- {
- int i;
- srand((unsigned)time(NULL));
- for(i=1; i<MAX; i++)
- num[i]=rand()%100;
- }
- void output(int num[])
- {
- int i;
- for(i=1; i<MAX; i++)
- {
- printf("%5d", num[i]);
- if(0==i%10)
- printf("/n");
- }
- }
-
int find(int num[],
- {
- int i;
- for(i=1; i<MAX; i++)
- if(x == num[i])
- return i;
- return 0;
- }
- void main()
- {
- int x, pos, num[MAX];
- input(num);
- printf("num...: /n");
- output(num);
- printf("Enter find num: ");
- scanf("%d", &x);
-
pos=find(num, x);
- if(pos)
- printf("OK! %d is found in pos: %d/n", x, pos);
- else
- printf("Sorry! %d is not found... in num/n", x);
- }
執行結果:
==========================================================
2、 折半查詢
在有序數列中,逐步縮小查詢範圍,直至找到或找不到記錄為止
本演算法首先隨機生成100個無序數列,然後利用快速排序演算法排序成有序數列,然後再用折半查詢演算法
說明:本演算法中的排序演算法,可用上一篇排序演算法中的任一種演算法實現,如選擇排序、氣泡排序、快速排序等
測試環境:VC 6.0 (C)
[cpp] view plain copy print?- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define MAX 101
- void input(int num[])
- {
- int i;
- srand((unsigned)time(NULL));
- for(i=1; i<MAX; i++)
- num[i]=rand()%100;
- }
- void output(int num[])
- {
- int i;
- for(i=1; i<MAX; i++)
- {
- printf("%5d", num[i]);
- if(0==i%10)
- printf("/n");
- }
- }
- void sort(int num[], int low, int high) /* quick sort */
- {
- int l, h;
- if(low<high)
- {
- l=low;
- h=high;
- num[0]=num[l]; /* save pivot */
- while(l<h)
- {
- while(l<h && num[h]>=num[0]) h--;
- num[l]=num[h];
- while(l<h && num[l]<=num[0]) l++;
- num[h]=num[l];
- }
- num[l]=num[0]; /* insert pivot */
- sort(num, low, l-1);
- sort(num, l+1, high);
- }
- }
- int find(int num[], int x, int low, int high)
- {
- int mid;
- while(low<=high)
- {
- mid=(low+high)/2; /* find is OK */
- if(x==num[mid])
- return mid;
- elseif(x<num[mid])
- high=mid-1;
- else
- low=mid+1;
- }
- return 0;
- }
- void main()
- {
- int x, pos, num[MAX];
- input(num);
- printf("sort before... /n");
- output(num);
- sort(num, 1, MAX-1);
- printf("sort after... /n");
- output(num);
- printf("Enter find num: ");
- scanf("%d", &x);
- pos=find(num, x, 1, MAX-1);
- if(pos)
- printf("OK! %d is found in pos: %d/n", x, pos);
- else
- printf("Sorry! %d is not found... in num/n", x);
- }
執行結果: