zoukankan      html  css  js  c++  java
  • c堆排序的实现

    堆排序的实现如下,用法与qsort相似:

    static void swap(void* a, void* b, int size)
    {
        char t;
    
        do {
            t = *(char*)a;
            *(char*)a++ = *(char*)b;
            *(char*)b++ = t;
        } while (--size > 0);
    }
    /* custom function cmp */
    void sort(void* base, size_t num, size_t size, int (*cmp)(const void*, const void*))
    {
        /* pre-scale counters for performance */
        int i = (num / 2 - 1) * size, n = num * size, c, r;
    
        /* heapify */
        for (; i >= 0; i -= size) {
            for (r = i; r * 2 + size < n; r = c) {
                c = r * 2 + size;
                if (c < n - size && cmp(base + c, base + c + size) < 0)
                    c += size;
                if (cmp(base + r, base + c) >= 0)
                    break;
                swap(base + r, base + c, size);
            }
        }
    
        /* sort */
        for (i = n - size; i > 0; i -= size) {
            swap(base, base + i, size);
            for (r = 0; r * 2 + size < i; r = c) {
                c = r * 2 + size;
                if (c < i - size && cmp(base + c, base + c + size) < 0)
                    c += size;
                if (cmp(base + r, base + c) >= 0)
                    break;
                swap(base + r, base + c, size);
            }
        }
    }
  • 相关阅读:
    [JSOI2016]最佳团体
    CF125E MST Company
    CF482C Game with Strings
    CF379F New Year Tree
    CF1051F The Shortest Statement
    小a和uim之大逃离
    新魔法药水
    翻硬币
    [CQOI2017]小Q的棋盘
    UVA11729突击战
  • 原文地址:https://www.cnblogs.com/tongyishu/p/12228256.html
Copyright © 2011-2022 走看看