c++实现顺序查找,折半查找

#include<stdio.h>
#include<iostream>
using namespace std;

#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int

typedef 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位置插入元素e
void 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;
	else
		cout <<"顺序查找:元素"<< 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; }
		else
		if (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");
}

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sky@sea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值