zoukankan      html  css  js  c++  java
  • Heapsort

    Heap是完全二叉树,所以可以用数组来隐式表示。对Heap的通常操作是删除和插入。删除就是去掉Heap的顶元素,然后重新建Heap.
    思想是,令Heap[1]=Heap[n],然后调整这个Heap即可。

    插入操作类似,只是从底部调整这个Heap;
    n++;
    child=n;
    parent=n/2;
    while(parent>=1)
    {
     if([parent]<[child])
     {
      swap([parent],[child]);
      child=parent;
      parent=child/2;
     }
     else break; 
    }

    Heap排序包括两个步骤:
    1,建立Heap;
    2,排序

    建立Heap可以自上而下,也可以自下而上,后者效率更高,因为是从n/2处开始做调整的。

    C实现:
    /* Heap sort */

    void display_x(int x[])
    {
     int i;
     for(i=1;i<=16;i++)
     {
      printf("%d ",x[i]);
     }
    }
    void swap(int *p1,int *p2)
    {
     int temp;
     temp=*p1;
     *p1=*p2;
     *p2=temp;
    }
    void build_heap(int x[],int n)
    {
     int child,temp_child;
     int parent,temp_parent;

     parent=n/2;
     child=parent*2;

     while(parent > 0)
     {
      if(child+1 <= n && x[child] < x[child+1])
      {
       child++;
      }
      if(x[child] > x[parent])
      {
       swap(&x[child],&x[parent]);
       /* adjust */
       temp_parent=child;
       temp_child=temp_parent*2;

       while(temp_child <= n-1)
       {
        if(x[temp_child] < x[temp_child+1])
        {
         temp_child++;
        }
        if(x[temp_child] > x[temp_parent])
        {
         swap(&x[temp_child],&x[temp_parent]);
         temp_parent=temp_child;
         temp_child*=2;
        }
        else
        {
         temp_child=n;
        }
       }
      }
      parent--;
      child=parent*2;
     }
    }

    void rearrange_heap(int x[],int n)
    {
     int parent;
     int child;

      parent=1;
      child=2;
      while(child <= n-1)
      {
       if(x[child] < x[child+1])
       {
        child++;
       }
       if(x[child] > x[parent])
       {
        swap(&x[child],&x[parent]);
        parent=child;
        child*=2;
       }
       else
       {
        child=n;
       }
      }
    }

    void heap_sort(int x[],int n)
    {
     int i;

     build_heap(x,n);
     display_x(x);
     for(i=n;i>=2;i--)
     {
      swap(&x[1],&x[i]);
      rearrange_heap(x,i-1);

     }
     printf("\n");
     display_x(x);
    }

    main()
    {
     int x[17]={0,6,2,8,5,10,9,12,1,15,7,3,13,4,11,16,14};
     int i;

     clrscr();

     heap_sort(x,16);
    }

  • 相关阅读:
    poj3126--Prime Path(广搜)
    iOS中 imageNamed方法 非常多图片占用大量内存问题
    容器+AOP实现动态部署(四)
    SpringBoot整合redis哨兵主从服务
    LINUX安装REDIS集群
    软件安装
    如何优雅地用Redis实现分布式锁
    Redis面试总结
    OAuth2.0 知多少(好)
    一张图搞定OAuth2.0
  • 原文地址:https://www.cnblogs.com/caca/p/731668.html
Copyright © 2011-2022 走看看