今天上午还得上最后半天班,数着时间一分一秒,实在是无聊至极。唉!练习练习算法打发时间吧!先写通用快排。
快排最主要的是确定枢轴并将枢轴定位,确定枢轴是比较有技术含量的,基于我是打发时间,所以就不给自己找别扭了,还是来点easy的吧!
代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int partition(void* arr, int(*cmp)(void*, void*), int left, int right, int size)
{
char* tmp = (char*)malloc(size);
memcpy(tmp, (char*)arr + left * size, size);
while (left < right)
{
while (left < right && cmp((char*)arr + right * size, (char*)tmp) >= 0)--right;
memcpy((char*)arr + left * size, (char*)arr + right * size, size);
while (left < right && cmp((char*)arr + left * size, (char*)tmp) <= 0)++left;
memcpy((char*)arr + right * size, (char*)arr + left * size, size);
}
memcpy((char*)arr + right * size, (char*)tmp, size);
return right;
}
static void quicksort(void* arr, int(*cmp)(void*, void*), int left, int right, int size)
{
if (right <= left)
return;
int part = partition(arr, cmp, left, right, size);
quicksort(arr, cmp, left, part - 1, size);
quicksort(arr, cmp, part + 1, right, size);
}
void qsort(void* arr, int n, int(*cmp)(void*, void*), int size)
{
quicksort(arr, cmp, 0, n - 1, size);
}