基于链表的顺序查找和折半查找——数据结构实习

#pragma once
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iomanip>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE 30
using namespace std;

typedef int KeyType;
typedef char OtherType;

typedef struct {
	KeyType key;
	OtherType other_data;
}ElemType;

typedef struct {
	ElemType *elem;
	int length;
}SSTable;

void CreateSSTable(SSTable &ST) {
	int n;
	ST.elem = (ElemType*)malloc(MAXSIZE*sizeof(ElemType));
	cout<<"输入你想创建的表的长度,最大不超过30"<<endl;
	cin>>n;
	cout<<"依次输入你想创建的表的主关键字和次关键字"<<endl;
	for(int i=1;i<=n;i++)
		cin>>ST.elem[i].key>>ST.elem[i].other_data;
}
//基于主关键的查找 
int Search(SSTable ST, KeyType key) {
	int i = ST.length;
	ST.elem[0].key = key;
	while(ST.elem[i].key != key)
		i--;
	return i;
}

int Binary_Search(SSTable ST, KeyType key) {
	int low = 1, high = ST.length;
	while(low <= high) {
		int mid = (low + high) / 2;
		if(ST.elem[mid].key == key)
			return mid;
		else if(ST.elem[mid].key >key)
			low = mid + 1;
		else high = mid - 1;
	}
	return 0;
}

//基于次关键字的查找 
char Search(SSTable ST, OtherType other_data) {
	int i = ST.length;
	ST.elem[0].other_data = other_data;
	while(ST.elem[i].other_data != other_data)
		i--;
	return i;
}

int main() {
	SSTable ST;
	CreateSSTable(ST);
	KeyType key;
	cout<<"输入你想查找的主关键字"<<endl;
	cin>>key;
	KeyType tmp1 = Search(ST, key);
	KeyType tmp2 = Binary_Search(ST, key);
	if(tmp1 == 0)
		cout<<"查找失败"<<endl;
	else cout<<"在第 "<<tmp1<<" 个位置"<<endl;
	
	if(tmp2 == 0)
		cout<<"查找失败"<<endl;
	else cout<<"在第 "<<tmp2<<" 个位置"<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40830622/article/details/80833353