


C/C++培训
达内IT学院
400-996-5531

今天给大家分享的是有关于算法的基本内容,关于算法的重要性无需多言,而我认为对于我们初学者来说,牢牢地记住几个常用的简单算法是非常有必要的。
以下是代码:
头文件:
#pragma once
# include<vector>
using namespace std;
class Binarysearch {
public:
Binarysearch(int);
int binarysearch(int)const;
void displayelements()const;
private:
int size;
vector<int>data;
void displaysubelements(int, int)const;
};
主函数:
# include<iostream>
# include<cstdlib>
# include<ctime>
# include<algorithm>
using namespace std;
# include"标头.h"
Binarysearch::Binarysearch(int vectorsize) {//此函数为制作一组随机数组
size = (vectorsize > 0 ? vectorsize : 10);
srand(time(0));
for (int i = 0; i < size; i++) {
data.push_back(10 + rand() % 90);//此处data.push_back的执行情况是将括号中随机产生的放入至我们在头文件定义的私有数据成员data容器内,并且每次都将数据放在容器的末尾。
}
std::sort(data.begin(), data.end());//此处语句利用了头文件库函数algorithm对我们的容器data中的数据进行排序!
}
int Binarysearch::binarysearch(int searchelement)const {
int low = 0;//data中的第一个数据
int high = size - 1;//data 中的最后一个数据位置
int middle = (low + high + 1) / 2;
int location = -1;
do {
displaysubelements(low, high);//这个语句在此处的作用是输出现有的数据。因为其参数low,high会因为循环而发生变化。
for (int i = 0; i < middle; i++) {
cout << " ";//请注意,此处空格为三个!极为重要!
}
cout << " * " << endl;//请注意空格。
if (searchelement == data[middle]) {
location = middle;//此处是如果我们要寻找的值恰好是中间值,则会返回当前位置。
}
else if (searchelement < data[middle]) {
high = middle - 1;
}//如果我们输入的值小于中间值时,我们data容器的最大成员下标为middle-1,即抛弃中间值之后的数据。
else {
low = high + 1;//抛弃中间值之前的数据
}
middle = (low + high + 1) / 2;//此处我们设置一个新的中间值。
} while ((low <= high) && (location == -1));
return location;
}
void Binarysearch::displayelements()const {
displaysubelements(0, size - 1);
}
void Binarysearch::displaysubelements(int low, int high)const {//此函数的作用便是输出现有的数据,请注意空格数量,其直接影响表示结果!
for (int i = 0; i < low; i++) {
cout << " ";
}
for (int i = low; i <= high; i++) {
cout << data[i] << " ";
}
cout << endl;
}
实现:
# include<iostream>
using namespace std;
# include"标头.h"
int main() {
int searchint;
int position;
Binarysearch searchvector(15);
searchvector.displayelements();
cout << "\n please enter an integer value(-1 to quit):";
cin >> searchint;
cout << endl;
while (searchint != -1) {
position = searchvector.binarysearch(searchint);
if (position == -1) {
cout << "the integer" << searchint << "was not found.\n" << endl;
}
else {
cout << "the integer" << searchint << "was found in position"
<< position << ".\n";
}
cout << "\n\nplease enter an integer value(-1 to quit):";
cin >> searchint;
cout << endl;
}
system("pause");
return 0;
}
基本上一些难以理解的地方我都已经用注释标注了,事实上,我看代码的习惯,一般是直接看实现的过程,而少看主函数体。但这里我还是选择了标注了主函数的注释。小伙伴们如果有问题的话,可与我留言讨论。
知识点1:首先要说的是其实二分法显而易见的并非是一种高效的查找算法,但是在一些频繁查找数据的领域还是具有应用性的。简而言之就是,二分法查找是将现有的数据进行排序之后,再用二分的方法,查找数据。本篇代码亦是如此,首先初始化了一个15个数据的容器data,使用库函数algorithm对其进行排序,然后进行二分查找。
知识点2:本篇代码实现的关键点不在于代码,而在于我注释中特别强调了的空格数量,如果小伙伴们想要重现的话,必须注意此点。
填写下面表单即可预约申请免费试听!怕钱不够?可就业挣钱后再付学费! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!
Copyright © 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有