使用C语言通过冒泡排序模拟实现sort
思路:调用模拟的sort,首先函数中,有多种类型的数组要进行排序,使用void*类型,因为需要排序其它类型数组所以需要修改冒泡排序中的交换条件和交换函数。
1.设计模拟sort排序函数
void bubble_sort(void* base,int sz,size_t wedth,int(*cmp)(void*,void*))
2.修改冒泡排序内容中的比较方法
int int_cmp(const void* e1,const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
3.修改修改冒泡排序内容中的交换方法
void swap(void* e1, void* e2,int sz)
{
int i = 0;
for (i = 0;i < sz; i++)
{
char tmp = *((char*)e1 + i);
*((char*)e1 + i) = *((char*)e2 + i);
*((char*)e2 + i) = tmp;
}
}
总代码如下
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int int_cmp(const void* e1,const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
void swap(void* e1, void* e2,int sz)
{
int i = 0;
for (i = 0;i < sz; i++)
{
char tmp = *((char*)e1 + i);
*((char*)e1 + i) = *((char*)e2 + i);
*((char*)e2 + i) = tmp;
}
}
void bubble_sort(void* base,int sz,size_t wedth,int(*cmp)(void*,void*))
{
for (int i = 0; i < sz; i++)
{
for (int j = 0; j < sz - i - 1; j++)
{
if (cmp((char*)base+j*wedth,(char*)base+(j+1)*wedth)>0)
{
swap((char*)base + j * wedth,(char*)base + (j + 1) * wedth, wedth);
}
}
}
}
int main(void)
{
int arr[] = { 9,5,6,7,2,0,1,4,3,8 };
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), int_cmp);
for (i = 0; i < sz; i++)
{
printf("%d ",arr[i]);
}
printf("\r\n");
return 0;
}