折半查找和冒泡排序

本文介绍了如何在C++中使用控制台交互方式实现冒泡排序和折半查找算法,通过动态分配内存创建数组,并展示了整个过程中的代码和实验结果。
摘要由CSDN通过智能技术生成

代码设计思路

使用用控制台控制输入的方式实现冒泡排序和折半查找,通过动态分配内存进行实验,代码如下:

#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; //释放被动态分配的内存
}

实验结果展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值