[排序]堆排序

注意

  • 有小到大排序

说明

  1. unsorted[ ] 为未排序数组
  2. length 为未排序数组长度

使用方法

  1. heap_sort _asc(数组,长度)

模板

void maxheap_down(int unsorted[], int start, int end)
{
    int c = start;            // 当前(current)节点的位置
    int l = 2*c + 1;        // 左(left)孩子的位置
    int tmp = unsorted[c];            // 当前(current)节点的大小
    for (; l <= end; c=l,l=2*l+1)
    {
        if ( l < end && unsorted[l] < unsorted[l+1])
            l++;        // 左右两孩子中选择较大者,即m_heap[l+1]
        if (tmp >= unsorted[l])
            break;        // 调整结束
        else            // 交换值
        {
            unsorted[c] = unsorted[l];
            unsorted[l]= tmp;
        }
    }
}

void heap_sort_asc(int unsorted[], int length)
{
    for (int i = length / 2 - 1; i >= 0; i--)
        maxheap_down(a, i, length-1);
    for (i = length - 1; i > 0; i--)
    {
        swap(unsorted[0], unsorted[i]);
        maxheap_down(unsorted, 0, i-1);
    }
}

results matching ""

    No results matching ""