• C语言qsort()函数的实现


    #include <stdio.h>
    void qsort(void * base, int num, int width, int (*comp)(const void *, const void *));
    void sort(char * lo, char * hi, int (*comp)(const void *, const void *), int width);
    char * partition(char * lo, char * hi, int (*comp)(const void *, const void *), int width);
    void swap(char * a, char * b, int width);
    int mycomp(const void * p1, const void * p2);
    
    int main(void) {
    	int i;
        int a[10] = {5, 3, 2, 9, 12, 6, 7, 10, 11, 1};
    	qsort(a, 10, 4, mycomp);
    	for (i = 0; i < 10; i++)
    		printf("%d ", a[i]);
    	printf("
    ");
    
    	return 0;
    }
    
    int mycomp(const void * p1, const void * p2) {
    	const int * a1 = (const int *) p1; 
    	const int * a2 = (const int *) p2;
    	if (*a1 < *a2)	
    		return -1;
    	else if (*a1 == *a2)
    		return 0;
    	else 
    		return 1;
    }
    
    void qsort(void * base, int num, int width, int (*comp)(const void *, const void *)) {
        char * lo = (char *) base;
        char * hi = (char *) base;
        hi += (num - 1) * width;
        sort(lo, hi, comp, width);
    }
    
    void sort(char * lo, char * hi, int (*comp)(const void *, const void *), int width) {
        char * p;
        if (lo >= hi)    return;
    
        p = partition(lo, hi, comp, width);
        sort(lo, p - width, comp, width);
        sort(p + width, hi, comp, width);
    }
    
    char * partition(char * lo, char * hi, int (*comp)(const void *, const void *), int width) {
        char * i = lo;
    	char * j = hi;
    
        while (i <= j) {
            do {
                i += width;
                if (i == hi)   break;
            } while ((*comp)(i, lo) < 0);
            
            while (1) {
    			if ((*comp)(j, lo) <= 0)
    				break;
    			j -= width;
    		}
            
            if (i <= j) 
                swap(i, j, width);
        }        
        swap(j, lo, width);
        return j;
    }
    
    //swap one byte at a time
    void swap(char * a, char * b, int width) {
        char tmp;
        while (width--) {
            tmp = *a;
            *a++ = *b;
            *b++ = tmp;
        }
    }

  • 相关阅读:
    P2832 行路难
    P2634 [国家集训队]聪聪可可
    模拟退火算法
    洛谷 P2986 [USACO10MAR]Great Cow Gat…(树形dp+容斥原理)
    bzoj1040: [ZJOI2008]骑士(基环树dp)
    洛谷P2014 选课(树形dp)
    洛谷P3047 [USACO12FEB]Nearby Cows(树形dp)
    bzoj1026: [SCOI2009]windy数(数位dp)
    hdu3555Bomb(数位dp)
    hdu3652B-number(数位dp)
  • 原文地址:https://www.cnblogs.com/zhayujie/p/7534858.html
Copyright © 2020-2023  润新知