|
我根据<<数据结构>>中描述的算法,用C语言实现的直接插入排序法:
[code:1]
#include <stdio.h>
#include <stdlib.h>
int insertSort(char *buf);
int main(){
char buf[] = "hgsdkaslda";
printf("%s\n", buf);
insertSort(buf);
printf("%s\n", buf);
}
int insertSort(char *buf)
{
char tmp;
char *tmpbuf;
int len;
int i, j;
len = strlen(buf);
tmpbuf = malloc(len +1);
*tmpbuf = *buf;
memcpy(tmpbuf +1, buf, len);
for(i = 2; i <= len; i++) {
if ( tmpbuf[i] < tmpbuf[i-1] ) {
tmpbuf[0] = tmpbuf[i];
for(j = i-1; tmpbuf[0] < tmpbuf[j]; --j)
tmpbuf[j+1] = tmpbuf[j];
tmpbuf[j+1] = tmpbuf[0];
}
}
memcpy(buf, tmpbuf+1, len);
return len;
}
[/code:1] |
|