应用场景:
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 ",arr_size); pt=(int *)malloc(sizeof(int)*arr_size); if(!pt){fprintf(stderr," can't malloc memory ");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 "); } 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 ",pos); *(parr+pos)|=(1<<(pos&mask)); } void clsBit(int n,int *parr) { int pos=n>>shift; // printf("clsBit pos : %d ",pos); *(parr+pos)&=(~(1<<(pos&mask))); } int isOne(int elem,int *parr) { int pos=elem>>shift; int flag= *(parr+pos)&(1<<(pos&mask)); //printf(" isOne:%d ",flag); return flag; } void test() { int *parr=bitVect(6); int arr[6]={1,5,4,3,2,6}; printf("reginal data : "); int i=1; for(;i<=6;i++) { clsBit(i,parr); if(i==6) { printf("%d ",arr[i-1]); } else { printf("%d,",arr[i-1]); } } printf(" "); i=0; for(;i<=6;i++) { setBit(arr[i-1],parr); } i=1; printf("sort data : "); for(;i<=6;i++) { if(isOne(i,parr)) { if(i==6) { printf(" %d ",i); } else { printf(" %d,",i); } } } printf(" bitFree(%p) :%d ",parr,bitFree(parr)); } int main(void) { test(); return 0; }