• 堆排序


    #include<iostream>
    using namespace std;
    
    int parent(int i)
    {
        return i/2;
    }
    
    int left(int i)
    {
        return 2*i;
    }
    
    int right(int i)
    {
        return 2*i + 1;
    }
    
    void swap(int &a, int &b)
    {
        int t = a;
        a = b;
        b = t;
    }
    
    void max_heapify(int arr[],int size, int i)
    {
        int l = left(i);
        int r = right(i);
        int largest = i;
        if(l<size && arr[l]>arr[largest])
            largest = l;
        if(r<size && arr[r] > arr[largest])
            largest = r;
        if(largest != i)
        {
            swap(arr[i], arr[largest]);
            max_heapify(arr,size,largest);
        }
    }
    
    void build_max_heap(int arr[],int size)
    {
        int i = 0;
        for(i=size/2; i>=0; i--)
            max_heapify(arr,size,i);
    }
    
    
    
    void print_arr(int arr[], int size)
    {
        for(int i=0; i<size; i++)
            cout<<arr[i]<<" ";
        cout<<endl;
    }
    
    void heapsort(int arr[], int size)
    {
        cout<<"before heap sorting..."<<endl;
        print_arr(arr,size);
        int heap_size = size;
        build_max_heap(arr,size);
        for(int i=size-1; i>0; i--)
        {
            swap(arr[0],arr[i]);
            heap_size--;
            max_heapify(arr,heap_size,0);
        }
        cout<<"After heap sorting..."<<endl;
        print_arr(arr,size);
    }
    
    
    int main()
    {
        int i = 0;
        int n;
        int arr[1000];
        cout<<"please input the size of array!"<<endl;
        cin>>n;
        cout<<"plead input the "<<n<<" numbers!"<<endl;
    
        for(i = 0; i<n; i++)
            cin>>arr[i];
        heapsort(arr,n);
        return 0;
    }
    多学习,多总结。
  • 相关阅读:
    xmpp1
    综合
    CSS进阶(一)width & height
    CSS进阶(二)content
    TypeScript 学习笔记-JSDoc
    TypeScript学习笔记-声明合并
    TypeScript 学习笔记-模块
    TypeScript学习笔记-高级类型
    TypeScript学习笔记-类型兼容性
    TypeScript学习笔记-枚举
  • 原文地址:https://www.cnblogs.com/yanhaiming/p/2954728.html
Copyright © 2020-2023  润新知