C 实现位图排序
应用场景:
1到N的不重复乱序数据,乱序数据总最大不超过N,需要高效的排序。
sorr.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define mask 0x1F #define shift 5 /************************** * function name: bitVect * description :according size to malloc memory * params : * size --input array size,every element in array can't over size * return : return a fixed memory *************************/ int *bitVect(int size) { int arr_size=0; int *pt=NULL; if((size%(1<<shift))==0) { arr_size=size/(1<<shift); } else { arr_size=(size/(1<<shift))+1; } printf(" malloc sizeof(int) count :%d\n",arr_size); pt=(int *)malloc(sizeof(int)*arr_size); if(!pt){fprintf(stderr," can't malloc memory \n");return NULL;} memset(pt,0,arr_size); return pt; } /************************* * function name: bitFree * description :free a memory named target * params : * target --a pointer that is needed to free * return : if opertation is ok,that return 1 * ***********************/ int bitFree(void *target) { if(target!=NULL) { free(target); target=NULL; printf(" target free ok\n"); } else { return 1; } return 0; } /*********************** * function name:setBit * description :set bit value in one element from array * params : * * *********************/ void setBit(int elem,int *parr) { int pos=elem>>shift; //printf(" pos = %d\n",pos); *(parr+pos)|=(1<<(pos&mask)); } void clsBit(int n,int *parr) { int pos=n>>shift; // printf("clsBit pos : %d\n",pos); *(parr+pos)&=(~(1<<(pos&mask))); } int isOne(int elem,int *parr) { int pos=elem>>shift; int flag= *(parr+pos)&(1<<(pos&mask)); //printf("\tisOne:%d\n",flag); return flag; } void test() { int *parr=bitVect(6); int arr[6]={1,5,4,3,2,6}; printf("reginal data :\n"); int i=1; for(;i<=6;i++) { clsBit(i,parr); if(i==6) { printf("%d\n",arr[i-1]); } else { printf("%d,",arr[i-1]); } } printf("\n"); i=0; for(;i<=6;i++) { setBit(arr[i-1],parr); } i=1; printf("sort data :\n"); for(;i<=6;i++) { if(isOne(i,parr)) { if(i==6) { printf(" %d\n",i); } else { printf(" %d,",i); } } } printf(" bitFree(%p) :%d\n",parr,bitFree(parr)); } int main(void) { test(); return 0; }