之前看过一些算法,都不是太留意,如今有时间,倒是想将之整理一二,如果错误之处,欢迎指正
Int16位整数字节交换,简单移位运算后或运算
static inline uint16_t bswap_16(uint16_t x)
{
return (x >> 8) | (x << 8);
}
int32位长整型字节交换
static inline uint32_5 bswap_32(uint32_t x)
{
x = ((x << 8) &0xFF00FF00) | ((x>>8)&0x00FF00FF);
return (x >> 16) | (x << 16);
}
知道结构体中某字段位置,偏移到结构体首部
#define CONTAINING_RECORD(address,type,field) ((type *)(((ULONG_PTR)address) - (ULONG_PTR)(&(((type *)0)->field))))
外部模块导入函数定义的宏
#define DECL_FUNCINTRO(call,ret,name,args) \
typedef ret (call *name ## _func) args; \
ret call new_ ## name args; \
extern name ## _func orig_ ## name; \
extern name ## _func load_ ## name;
#define LIBRARY_LOADFUNC(dll,func) \
{ \
HMODULE hDll = LoadLibrary(dll); \
if(hDll) { \
load_ ## name = (name ## _func)GetProcessAddress(hDll,# name); \
} \
}
冒泡排序算法简述
void bubble_sort(int a[],int n)
{
for(int i = 0;i<n-1;i++)
{
for(int j = 0;j<n-1-i;j++)
{
if(a[j] > a[j+1])
{
int temp =a[j]; a[j] = a[j+1];a[j+1]=a[j];
}
}
}
}
快速排序
int partition(int *data,int low,int hign)
{
int t = 0;
t = data[low];
while(low < high)
{
while(low < high && data[high] >= t)
high --;
data[low] = data[high];
while(low < high && data[low] < t)
low++;
data[high] = data[low];
}
data[low] = t;
return low;
}
void quick_sort(int *data,int low,int high)
{
if(low <= high) return;
int pivotloc = 0;
pivotloc = partition(data,low,high);
quick_sort(data,low,pivotloc-1);
quick_sort(data,pivotloc-1,high);
}
或者直接写出函数实现
void quick_sort(int s[],int l,int r)
{
if(l< r)
{
int i = l,j= r,x=s[l];
while(i < j)
{
while(i<j && s[j] >= x)
j--;
if(i < j)
s[i++] = s[j];
while(i < j && s[i] < x)
i++;
if(i < j)
s[j--] = s[i];
}
s[i] = x;
quick_sort(s,l,i - 1);
quick_sort(s,i+ 1,r);
}
}
选择排序
static void selection_sort(int a[],int n)
{
for(int i = 0;i<n;i++)
{
int min = a[i],min_index = i;
for(int j = i;j<n;j++)
{
if(a[j] < min)
{
min = a[j];
min_index = j;
}
}
if(min_index != i)
{
int temp = a[i];
a[i] = a[min_index];
a[min_index] = temp;
}
}
}
堆排序
void heap_sort(int a[],int i)
{
int j ,temp;
temp = a[i];
j = (i - 1) /2;
while(j >= 0 && i != 0)
{
if (a[j] <= temp) break;
a[i] = a[j];
i = j;
j = (i - 1)/2;
}
a[i] = temp;
}