直接上代码
若代码有可优化或某处不合理,欢迎指正,不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare_double(void* dst_addr, void* src_addr)
{
return (*(double*)dst_addr > *(double*)src_addr);
}
int compare_char(void* dst_addr, void* src_addr)
{
return (*(char*)dst_addr > *(char*)src_addr);
}
int compare_int(void* dst_addr, void* src_addr)
{
return (*(int*)dst_addr > *(int*)src_addr);
}
void select_sort_all_type(void* arr, int len, int elem_size, int(*)(void*, void*));
void blue_sort_all_type(void* arr, int len, int elem_size, int (*compare)(void*, void*));
int main(int argc, char* argv[])
{
int arr[8] = {43, 56, 34, 23, 42, 78, 96, 73};
char buf[] = "hello world";
double num[7] = {3.2, 3.1, 5.4, 3.0, 6.7, 4.3, 2.9};
int i = 0;
// int类型数组回调
select_sort_all_type(arr, 8, sizeof(int), compare_int);
blue_sort_all_type(arr, 8, sizeof(int), compare_int);
for(i = 0; i < 8; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
// char类型数组回调
select_sort_all_type(buf, strlen(buf), sizeof(char), compare_char);
blue_sort_all_type(buf, strlen(buf), sizeof(char), compare_char);
printf("%s\n", buf);
// double类型数组回调
select_sort_all_type(num, 7, sizeof(double), compare_double);
blue_sort_all_type(num, 7, sizeof(double), compare_double);
for(i = 0; i < 7; i++)
{
printf("%lf ", num[i]);
}
printf("\n");
return 0;
}
void select_sort_all_type(void* arr, int len, int elem_size, int (*compare)(void*, void*))
{
void *i_addr = arr;
void *end_addr = arr + len*elem_size;
for(; i_addr < end_addr-elem_size; i_addr += 1*elem_size)
{
void *s_addr = i_addr;
void *j_addr = i_addr + 1*elem_size;
for(; j_addr < end_addr; j_addr += 1*elem_size)
{
if(compare(s_addr, j_addr))
{
s_addr = j_addr;
}
}
if(s_addr != i_addr)
{
void* tmp_addr = calloc(1, elem_size);
memcpy(tmp_addr ,s_addr ,elem_size);
memcpy(s_addr ,i_addr ,elem_size);
memcpy(i_addr ,tmp_addr ,elem_size);
free(tmp_addr);
}
}
return;
}
void blue_sort_all_type(void* arr, int len, int elem_size, int (*compare)(void*, void*))
{
void* end_addr = arr + len*elem_size;
int i = 0;
for(i = 0; i < len - 1; i++)
{
void* j_addr = arr;
for(;j_addr < end_addr - (i*elem_size) - elem_size; j_addr += 1*elem_size)
{
if(compare(j_addr, j_addr + elem_size))
{
void* t_addr = calloc(1, elem_size);
memcpy(t_addr, j_addr, elem_size);
memcpy(j_addr, j_addr+elem_size, elem_size);
memcpy(j_addr+elem_size, t_addr, elem_size);
free(t_addr);
}
}
}
return;
}
标签:size,compare,addr,int,void,elem,冒泡,排序,函数
From: https://www.cnblogs.com/qinghuan190319/p/17232489.html