<pre name="code" class="cpp"><span style="background-color: rgb(255, 255, 255);">// 插入排序
//
// O(n^2),在递增序列插入1个元素时,O(n)
#include "sort.h"
void issort(void *data, int size, int esize, int (*compare)(const void *key1, const void *key2))
{
int i, j;
int *a =(int *)data;
int *key;
// 为key申请空间
if ((key = (int *)malloc(sizeof(char))) != NULL)
{
return;
}
// 初始化j
j = 1;
while(j <= size) // j为待排序的元素, 一步一步向右移动
{
// key作为缓存
memcpy(key, &a[j], sizeof(int));
i = j - 1; // i从j的左边一个位置开始
while(i <= j)
{
if(compare(key, &a[i]) < 0) //a[j] < a[i]
{
memcpy(&a[i + 1], &a[i], sizeof(int)); // 整个数组向右移动一个位置
i--;
}
}
// 插入a[j]正确的位置
memcpy(&a[i + 1], key, sizeof(int));
j++;
}
free(key);
return;
}
</span>
算法精解(一)——插入排序
最新推荐文章于 2017-11-18 18:36:55 发布