码迷,mamicode.com
首页 > 编程语言 > 详细

堆排序

时间:2017-11-01 01:04:25      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:cto   uil   i++   std   public   int   char   stream   ace   

/*

 */

/*
 知识点:
 
 
 */

#include <iostream>
#include <map>
#include <vector>
#include <cstring>
#include <cstdio>
#include <climits>
using namespace std;

#define MAXN 1005


class heap_sort {
private:
    
public:
    void Swap(int &a,int &b)
    {
        int temp;
        temp=a;
        a=b;
        b=temp;
    }
    
    void max_heapify(int *A , int i, int len){
        int l = 2 * i;
        int r = 2 * i + 1;
        int largest;
        if (l <= len && A[i] < A[l]){
            largest = l;
        }
        else{
            largest = i;
        }
        if (r <= len && A[largest] < A[r])
            largest = r;
        if (largest != i){
            Swap(A[largest], A[i]);
            max_heapify(A,largest,len);
        }
    }
    
    void build_heap(int *A ,int len){
        for (int i = len/2; i >= 1; i--){
            max_heapify(A, i, len);
        }
    }
    
    void heapsort(int *A,int len){
        build_heap(A, len);
        for ( int i=len; i>=2; i--){
            Swap(A[i], A[1]);
            len = len -1;
            max_heapify(A, 1, len);
        }
    }
};

int main(int argc, const char * argv[]) {
    int arr[15];
    for(int i = 0; i <= 10; i++)
        cin >> arr[i];
    heap_sort ans;
    ans.heapsort(arr, 10);
    for(int i = 1; i <= 10; i++)
        cout << arr[i] << " ";
    cout << endl;
    return 0;
}

 

堆排序

标签:cto   uil   i++   std   public   int   char   stream   ace   

原文地址:http://www.cnblogs.com/WH-K/p/7764461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!