zoukankan      html  css  js  c++  java
  • 最大堆排序

    #include <iostream>
    #include <vector>
    using namespace std;
    
    inline int leftChild(int i)
    {
    	return 2*i+1;
    }
    
    template <typename Comparable>
    void percDown(vector<Comparable>& a,int i,int n)
    {
    	int child;
    	Comparable tmp;
    
    	for(tmp = a[i];leftChild(i) < n;i = child)
    	{
    		child = leftChild(i);
    		if(child != n-1 && a[child] < a[child+1])
    			child++;
    		if(tmp < a[child])
    			a[i] = a[child];
    		else
    			break;
    	}
    	a[i] = tmp;
    }
    
    template <typename Comparable>
    void heapSort(vector<Comparable>& a)
    {
    	for(int i =a.size()/2-1;i>=0;--i) //buildHeap
    		percDown(a,i,a.size());  
    	for(int j=a.size()-1;j>0;--j)
    	{
    		swap(a[0],a[j]);            //delete Max
    		percDown(a,0,j);
    	}
    }
    
    int main()
    {
    	vector<int> arr;
    	int data;
    	cin >> data;
    	while(data != -1)
    	{
    		arr.push_back(data);
    		cin>>data;
    	}
    	vector<int>::iterator iter = arr.begin();
    	for(;iter != arr.end();++iter)
    		cout << *iter << ' ';
    	cout << endl;
    	return 0;
    }
    

      

  • 相关阅读:
    多重背包
    摘花生
    完全背包问题
    01背包问题
    数字金字塔
    ES6 Object.assign()的用法
    umi---className设置多个样式
    npm 安装yarn
    html引入其他html的几种方式
    react打包去掉map文件
  • 原文地址:https://www.cnblogs.com/phoenixzq/p/2190520.html
Copyright © 2011-2022 走看看