zoukankan      html  css  js  c++  java
  • c语言 堆排序 多函数处理法

    灵感来源于YouTube一段根据堆排序(HeapSort)改编的舞蹈而来

    点击查看:YouTube高清无logo版Heapsort舞蹈

    B站搬运版Heapsort舞蹈

    #include <stdio.h>
    void swap(int tree[],int i,int j)//交换两值
    {
        tree[i]=tree[i]+tree[j]-(tree[j]=tree[i]);
    }
    void heapify(int tree[],int n,int i)//n表示n个数,i表示第i个节点
    {
        if(i>=n)
            return;
        int c1=2*i+1;
        int c2=2*i+2;
        int max=i;
        if(c1<n&&tree[c1]>tree[max])
            max=c1;
        if(c2<n&&tree[c2]>tree[max])
            max=c2;//记录坐标,方便下一步的heapify
        if(max!=i)
        {
            swap(tree,max,i);//交换值但不交换坐标
            heapify(tree, n, max);//从原较大的子树位置开始再做heapify
        }
    }
    void build_heap(int tree[],int n)//创建堆
    {
        int last_node=n-1;
        int parent=(last_node-1)/2;//找到最后一个非叶子结点,对其开始heapify
        for(int i=parent;i>=0;i--)//由最后一个非叶子结点开始,向前遍历所有非叶子结点
            heapify(tree,n,i);
    }
    void heapSort(int tree[],int n)
    {
        build_heap(tree, n);//创建一个堆
        for(int i=n-1;i>=0;i--)//开始堆处理
        {
            swap(tree,0,i);//将第一个数与最后一个数交换
            heapify(tree, i, 0);//再从 第一个数 开始做heapify,从而找出最大的数
        }
    }
    void print(int a[],int n)
    {
        for(int i=0;i<n;i++)
            printf("%d	",a[i]);
    }
    int main(){
        int arr[8]={7,3,1,5,8,2,4,6};
        int n=8;
        heapSort(arr, n);
        print(arr,n);
        printf("
    ");
    }
  • 相关阅读:
    python
    图片放大,缩小等操作
    template-web.js 自定义过滤器
    python
    python
    Android Volley源码分析及扩展
    Android 6.0动态权限申请教程
    Jarsigner签名使用
    Python正则表达式(总)
    Python错误和异常概念(总)
  • 原文地址:https://www.cnblogs.com/oldfish123/p/13171035.html
Copyright © 2011-2022 走看看