代码设计思路
使用用控制台控制输入的方式实现冒泡排序和折半查找,通过动态分配内存进行实验,代码如下:
#include<stdlib.h>
#include<iostream>
using namespace std;
int cnt = 0;
//折半查找实现,本次实习采用数组实现折半查找
int Halffind(int* list, int low, int high, int the_find) {
//list是待查找数组,low是低下标,high是高下标,the_find是待查找数据
cnt++; //定义迭代次数,可视化输出迭代次数
if (high < low) { //迭代终止条件
printf("待查找元素不存在||原数组输入错误");
return -1;
}
else {
int mid = (low + high) / 2;
if (list[mid] == the_find) {
printf("查找正确,已经找到。\n");
return mid;
}
else if (the_find < list[mid]) {
return Halffind(list, low, mid - 1, the_find);//查找元素小于中值
}
else {
return Halffind(list, mid + 1, high, the_find);//查找元素大于中值
}
}
}
//冒泡排序实现
void Bubble_rank(int* list, int len) {
//list是待排序数组,len是数组长度
//打印初次数组
cout << "待排数组为:";
for (int ct = 0; ct < len; ct++) {//打印输出结果
cout << list[ct]<<' ';
if (ct == len - 1) {
cout << endl;
}
}
//定义标志,进行判断排序次数
int flag = 0;
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1-i; j++) {
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
flag++;
cout << "第" << flag << "次排序结果: ";
for (int ct = 0; ct < len; ct++) {//打印输出结果
cout << list[ct] << ' ';
if (ct == len - 1) {
cout << endl;
}
}
}
}
int main() {
//交互式创建数组
cout << "请输入待排数组长度:";
int len = 0;
cin >> len;
//动态分配内存
int* list = new int[len];
//输入list元素
cout << "输入创建数组元素:" << endl;
for (int i = 0; i < len; i++) {
cout << "输入第" << i + 1 << "个元素: ";
cin >> list[i];
}
//冒泡排序
cout << "创建数组元素成功"<<endl<< "开始冒泡排序: "<<endl;
Bubble_rank(list, len);
//折半查找
cout << "冒泡排序成功!开始折半查找,请输入查找元素:";
int the_find = 0;
cin >> the_find;
int output = 0;//定义结果,没找到返回-1,找到返回索引
output = Halffind(list, 0, len-1, the_find);
if (output == -1) {
return 0;
}
else{
cout << "查找次数为:" <<cnt<<endl;
cout << "查找元素下标为:" << output + 1 <<endl<<"查找元素为:"<<list[output];//输出按照下标为1起算
return 1;
}
delete[] list; //释放被动态分配的内存
}