heap算法,binary_search
程序员文章站
2022-03-02 21:13:07
...
直接代码如下:
//heap算法
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
int main(){
int a[]={7,4,1,8,5,2,9,6,3,8};
vector<int>v(a,a+10);
make_heap(v.begin(),v.end());
for(vector<int>::iterator itera=v.begin();itera!=v.end();++itera){
cout<<*itera<<" ";
}
cout<<endl;
v.pop_back();
for(vector<int>::iterator itera=v.begin();itera!=v.end();++itera){
cout<<*itera<<" ";
}
cout<<endl;
pop_heap(v.begin(),v.end());//把最大的元素放到最后面
for(vector<int>::iterator itera=v.begin();itera!=v.end();++itera){
cout<<*itera<<" ";
}
cout<<endl;
v.pop_back();//把最大的元素删除了
for(vector<int>::iterator itera=v.begin();itera!=v.end();++itera){
cout<<*itera<<" ";
}
cout<<endl;
v.push_back(50);
push_heap(v.begin(),v.end());//列入根堆
for(vector<int>::iterator itera=v.begin();itera!=v.end();++itera){
cout<<*itera<<" ";
}
cout<<endl;
sort_heap(v.begin(),v.end());//v不再是根堆
for(vector<int>::iterator itera=v.begin();itera!=v.end();++itera){
cout<<*itera<<" ";
}
cout<<endl;
system("pause");
return 0;
}
//binary_search
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
int main(){
int a[]={7,4,1,5,6,9,8,2,3,8};
vector<int>v(a,a+10);
sort(v.begin(),v.end());//在调用binary_search的时候一定要先排序
if(binary_search(v.begin(),v.end(),6)){
cout<<"6 is present"<<endl;
}else{
cout<<"6 is not present"<<endl;
}
if(binary_search(v.begin(),v.end(),42)){
cout<<"42 is present"<<endl;
}else{
cout<<"42 is not preset"<<endl;
}
system("pause");
return 0;
}