实验内容:
对给定的序列分别采用顺序查找、折半查找算法,查找某个数,若查找成功,输出该数在序列中的序号;若查找不成功,输出提示信息。不管是否查找成功,均要输出查找过程中每次比较的元素。
- Search_A.cpp文件
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> #include "Search_A.h" using namespace std; //在顺序表ST中顺序查找其关键字等于key的数据元素。若找到,则函数值为该元素在表中的位置,否则为0 int Search_Seq(SSTable& ST, KeyType key) //顺序查找 { for (int i = 0; i < ST.length; i ++) { ST.R[i].otherinfo = ST.R[i].key; //将比较的值存入otherinfo if (ST.R[i].key == key) return i + 1; //从后往前查找 } return 0; } //在有序表ST中折半查找其关键字等于key的数据元素。若找到,则函数值为该元素在表中的位置,否则为0 int Search_Bin(SSTable& ST, KeyType key) //折半查找 { int low = 1; int mid; int high = ST.length; //置查找区间初值 int i = 0; while (low <= high) { mid = (low + high) / 2; ST.R[i].otherinfo = ST.R[mid].key; //将比较的值存入otherinfo i += 1; if (key == ST.R[mid].key) return mid + 1; //找到待查元素 else if (key < ST.R[mid].key) high = mid - 1; //继续在前一子表进行查找 else low = mid + 1; //继续在后一子表进行查找 } return 0; //表中不存在待查元素 }
- Search_A.h文件
#pragma once #ifndef Search_A_H #define Search_A_H #define KeyType int //宏定义特殊的返回类型为int #define InfoType int typedef struct { KeyType key; //关键字域 InfoType otherinfo; //其他域 }ElemType; typedef struct { ElemType R[20]; //存储空间基地址 int length; //当前长度 }SSTable; int Search_Seq(SSTable& ST, KeyType key); //顺序查找 int Search_Bin(SSTable& ST, KeyType key); //折半查找 #endif
- main.cpp文件
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> #include "Search_A.h" using namespace std; int main() { SSTable ST; int key, m = 0; cout << "输入序列长度:"; cin >> ST.length; //先输入该序列的长度 for (int i = 0; i <= ST.length; i++) //初始化ST里的值 { ST.R[i].key = 0; ST.R[i].otherinfo = 0; } cout << "输入序列元素:"; for (int i = 0; i < ST.length; i++) cin >> ST.R[i].key; //输入序列元素 cout << "输入要查找的元素:"; cin >> key; //输入要查找的元素 if (!Search_Seq(ST, key)) cout << "顺序查找-查无该元素。" << endl << endl; else cout << "顺序查找-查找成功,该元素在序列中的序号为" << Search_Seq(ST, key) << endl << endl; cout << "顺序查找-每次比较的元素:"; while (ST.R[m].otherinfo) { cout << ST.R[m].otherinfo << "\t"; //依次输出比较的值 m += 1; } cout << endl << endl; for (int i = 0; i <= ST.length; i++) //重置ST里依次比较的值 { ST.R[i].otherinfo = 0; } if (!Search_Bin(ST, key)) cout << "折半查找-查无该元素。" << endl << endl; //输出位置 else cout << "折半查找-查找成功,该元素在序列中的序号为" << Search_Bin(ST, key) << endl << endl; //输出位置 cout << "折半查找-每次比较的元素:"; m = 0; while (ST.R[m].otherinfo) { cout << ST.R[m].otherinfo << "\t"; //依次输出比较的值 m += 1; } cout << endl << endl; return 0; }