zoukankan      html  css  js  c++  java
  • 读书笔记 算法导论 堆排序

    感觉自己算法不给力额...对基本概念和基本操作都不够熟悉

    准备吧整个算法导论过一遍...把大部分常用的东西自己写一遍

    做it真是辛苦啊...

    先弄个常用的堆吧

    堆可以用作堆排序,优先队列等等情况

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;

    namespace IntroduceToAlgorithm
    {

    public class MaxHeap
    {
    /// <summary>
    /// check the node is obey Max_Heap_property or not
    /// </summary>
    /// <param name="A">an int array represent a heap</param>
    /// <param name="i">the node index</param>
    /// <param name="aLength">the arry length , (some time, we will reduce the length of array)</param>
    public void MaxHeapify(int[] A, int i, int aLength = -1)
    {
    int length = aLength <= -1 ? A.Length : aLength;

    var l
    = Left(i);
    var r
    = Right(i);
    int largest = i;

    if (l < length && A[l] > A[i])
    {
    largest
    = l;
    }

    if (r < length && A[r] > A[largest])
    {
    largest
    = r;
    }

    if (largest != i)
    {
    Exchange(A, i, largest);
    MaxHeapify(A, largest, aLength);
    }
    //MaxHeapify(A, l);
    //MaxHeapify(A, i);


    }

    public int Left(int index)
    {
    return (index + 1) * 2 - 1;
    }

    public int Right(int index)
    {
    return (index + 1) * 2;
    }

    public void Exchange(int[] A, int i, int i2)
    {
    int val = A[i];
    A[i]
    = A[i2];
    A[i2]
    = val;
    }

    /// <summary>
    /// build a max-heap, all element obey max-heap-property
    /// wo only need check element which index less than A.Length/2 -1
    /// </summary>
    /// <param name="A"></param>
    public void Build_Max_Heap(int[] A)
    {
    for (int i = (A.Length / 2 - 1); i >= 0; i--)
    {
    MaxHeapify(A, i);
    }

    }

    public void HeapSort(int[] A)
    {
    int length = A.Length;
    Build_Max_Heap(A);
    for (int i = A.Length - 1; i >= 1; i--)
    {
    Exchange(A,
    0, i);
    MaxHeapify(A,
    0, --length);
    }
    }

    }

    }

    PS:看伪代码有的时候很郁闷 例如C#数组下标开始是0,伪代码中一般是1  转换来转换去就乱了.......尴尬

  • 相关阅读:
    阿里巴巴
    实用得 JS 代码
    C#获得当前插入数据的ID
    “职场五魅”助你成功
    SQL2005导入导出数据库方法集合
    VS05里checkboxlist用JS获取 value值
    sql 去除html标签函数
    百度新闻搜索结果页的采集
    把表中的某个字段格式如:2,3,4的数据分别插入到另一个表中
    jquery 定位元素并获取数据
  • 原文地址:https://www.cnblogs.com/PurpleTide/p/2005880.html
Copyright © 2011-2022 走看看