赞
踩
- #include<stdio.h>
- #include<stdlib.h>
- #define MAXSIZE 50
- //定义线性表
- typedef struct
- {
- int elem[MAXSIZE];
- int length;
- }sqlist;
- //顺序查找
- int search(sqlist ST, int key)
- {
- int i;
- ST.elem[0] = key;
- for (i = ST.length; ST.elem[i] != key; --i);
- return i;
- }
- //折半查找
- int search_bin(sqlist ST, int key)
- {
- int low,high,mid;
- low = 1;
- high = ST.length;
- while (low <= high)
- {
- mid = (low + high) / 2;
- if (key == ST.elem[mid]) return mid;
- else if (key < ST.elem[mid]) high = mid - 1;
- else low = mid + 1;
- }
- return 0;
- }
- //创建线性表
- void create_list(sqlist*ST)
- {
- int i;
- printf("输入元素个数n\n");
- scanf("%d", &ST->length);
- for (i = 1; i <=ST->length; i++)
- {
- printf("\n data %d=?", i);
- scanf("%d", &(ST->elem[i]));
- }
- }
-
- int main()
- {
- sqlist ST;
- int key;
- create_list(&ST);
- printf("查找元素e=");
- scanf("%d", &key);
- printf("%d\n",search(ST, key));
- printf("%d\n",search_bin(ST, key));
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。