stl的排序 和 用算法实现的排序比较

#include<iostream>
#include<vector>
#include<iterator>
#include<functional>
#include<algorithm>
#include<string>
#include<fstream>
using namespace std;
template<class Type>
void swap1(Type &a,Type &b)
{
    Type temp=a;
    a=b;
    b=temp;
}
template<class Type>
void Perm(Type list[],int k,int m)
{
    if(k==m)
    {
        for(int i=0;i<=m;i++)
        cout<<list[i];
        cout<<endl;
    }
    else
    for(int i=k;i<=m;i++)
    {
        swap1(list[k],list[i]);
        Perm(list,k+1,m);
        swap1(list[k],list[i]);
    }
}




int main()
{
    cout<<"size:";
    int size;


    cin>>size;
    cout<<"filename:";
    string name;
    cin>>name;
    ofstream outfile(name.c_str(),ios::app);
    vector<int>coll;
    int *p=new int[size];
    for(int i=0;i<size;i++)
   {
      p[i]=i;
       coll.push_back(i);
   }
   Perm(p,0,size-1);
    do
    {
       copy(coll.begin(),coll.end(),
    ostream_iterator<int>(cout," "));
             for(int i=0;i<coll.size();++i)
             outfile<<coll[i];
             outfile<<endl;


    }while(next_permutation(coll.begin(),coll.end()));






}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
排序是一种基于堆的排序算法,它的时间复杂度为O(nlogn)。下面是使用STL算法和迭代器实现排序的示例代码: ```c++ #include <iostream> #include <vector> #include <algorithm> using namespace std; // 堆排序 template<typename T> void heapSort(vector<T>& array) { // 将数组转换为堆 make_heap(array.begin(), array.end()); // 依次取出堆顶元素并重新调整堆 for (int i = array.size() - 1; i > 0; i--) { // 取出堆顶元素 pop_heap(array.begin(), array.begin() + i + 1); // 将堆顶元素放到数组末尾 swap(array[0], array[i]); // 重新调整堆 adjust_heap(array.begin(), i); } } // 调整堆 template<typename T> void adjust_heap(T begin, int size) { int i = 0; int j = 2 * i + 1; T end = begin + size; while (j < size) { // 找出左右子节点较大的一个 if (j + 1 < size && *(begin + j) < *(begin + j + 1)) { j++; } // 如果父节点比子节点小,则交换父子节点的值 if (*(begin + i) < *(begin + j)) { swap(*(begin + i), *(begin + j)); i = j; j = 2 * i + 1; } else { break; } } } int main() { vector<int> array = {3, 6, 1, 8, 2, 4, 9, 5, 7}; heapSort(array); for (auto it = array.begin(); it != array.end(); it++) { cout << *it << " "; } return 0; } ``` 在上面的代码,我们首先使用make_heap函数将数组转换为堆,然后依次取出堆顶元素并重新调整堆,直到所有元素都被取出为止。在调整堆的过程,我们使用了自定义的adjust_heap函数,它用于将一个不符合堆定义的子树调整为堆。 运行结果为:1 2 3 4 5 6 7 8 9

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值