c++实现顺序查找,折半查找
来源:互联网 发布:java apache 框架 编辑:程序博客网 时间:2024/06/02 02:35
#include<stdio.h>#include<iostream>using namespace std;#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define ElemType inttypedef struct{ElemType *elem;int length;int listsize;}SqList;//建顺序表void InitList_Sq(SqList &L){L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));if (!L.elem) cout << "存储分配失败!" << endl;L.length = 0;L.listsize = LIST_INIT_SIZE;}//在第i位置插入元素evoid ListInsert_Sq(SqList &L, int i,ElemType e){int *newbase;if (i<1 || i>L.length + 1) cout << "位置错误!" << endl;if (L.length >= L.listsize){newbase = (ElemType *)realloc(L.elem, (L.listsize + LISTINCREMENT)*sizeof(ElemType));if (!newbase) cout << "重新分配地址错误!" << endl;L.elem = newbase;L.listsize += LISTINCREMENT;}int *p, *q;q = &(L.elem[i - 1]);for (p = &(L.elem[L.length - 1]); p >= q; --p)//将第i位置及其以后的元素后移一个位置*(p + 1) = *p;*q = e;++L.length;}//比较两个元素是否相等int EQ(int a, int b){if (a == b) return 1;else return 0;}//顺序查找void Search_Sq(SqList L, ElemType key){int *p,i=1;p = L.elem;while (i <= L.length && L.elem[i-1]!=key) ++i;if (i > L.length-1) cout << "不存在元素" << key << endl;elsecout <<"顺序查找:元素"<< key << "的位置是:" << i << endl;}//折半查找void Search_Bin(SqList L, ElemType key){int low, high, mid;low = 0;high =L.length - 1;while (low <high){mid = (low + high) / 2;if (EQ(key,L.elem[mid])) { cout << "折半查找:元素" << key << "的位置为:" << mid + 1 << endl; break; }elseif (key < L.elem[mid]) {high = mid - 1;}else{low = mid + 1;}}}void PrintL(SqList &L){int i = 0;while (i < L.length){cout << L.elem[i]<<" ";i++;}cout << endl;}void main(){SqList L;//创建顺序表La并插入数据InitList_Sq(L);ListInsert_Sq(L, 1, 12);ListInsert_Sq(L, 2, 25);ListInsert_Sq(L, 3, 39);ListInsert_Sq(L, 4, 56);ListInsert_Sq(L, 5, 78);ListInsert_Sq(L, 6, 80);ListInsert_Sq(L, 7, 86);ListInsert_Sq(L, 8, 88);ListInsert_Sq(L, 9, 91);ListInsert_Sq(L, 10, 95);ListInsert_Sq(L, 11, 98);ListInsert_Sq(L, 12, 99);cout << "La的元素为:";PrintL(L);//顺序查找Search_Sq(L, 91);//折半查找Search_Bin(L, 91);//防止运行结果一闪而过system("pause");}
阅读全文
0 0
- python实现顺序查找和折半查找
- c++实现顺序查找,折半查找
- 折半查找&顺序查找
- 查找:顺序查找,折半查找
- C语言 数据结构查找 顺序查找及折半查找
- 顺序查找和折半查找
- 顺序查找 折半查找 二叉排序树
- 顺序查找和折半查找
- 顺序查找和折半查找
- 顺序查找和折半查找
- 折半查找和顺序查找
- 折半查找和顺序查找
- 顺序查找和折半查找
- 顺序查找和折半查找
- 折半查找和顺序查找
- 查找算法的实现 顺序和折半
- C语言设置监视哨的顺序查找、折半查找算法的实现
- (3) 查找算法 --- 顺序查找 折半查找
- 几种将存储为str的其他类型转换回去的方法
- C#191课的主要内容
- mybatis mapper把传递来的参数当作字段写入结果集中
- Android代码混淆之混淆规则
- AI:IPPR的模式生成-学习/训练方式(基本结构)
- c++实现顺序查找,折半查找
- 插入排序
- ES中查询数据使用date_histogram时报错
- Java集合知识点总结
- ubuntu/var/log/下各个日志文件
- Python基础入门教程,Python学习路线图
- Unity声音-音源组件AudioSource
- 7.类加载器及双亲委派模型
- centos7编译安装redis-4.0.0