一、冒泡排序:
1、只能对整型数据进行冒泡排序
# define _CRT_SECURE_NO_WARNINGS 1
# include<stdio.h>
# include<stdlib.h>
# include<string.h>
void BubbleSort(int arr[], int sz)
{
int i = 0;
int j = 0;
for (i = 0; i < sz-1; i++)
{
for (j = 0; j < sz -1- i; j++)
{
if (arr[j] > arr[j + 1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
int main()
{
int arr[] = { 2, 1, 0, 9, 8, 7, 5, 6, 4, 3 };
int sz = sizeof(arr) / sizeof(arr[0]);
BubbleSort(arr, sz);
system("pause");
return 0;
}
2、优化,优化后不仅可以对整型数据进行排序,还可以对其他类型的数据进行排序
struct s
{
char name[20];
int age;
};
int cmp_int(const void *e1, const void *e2)//回掉函数
{
return *(int *)e1 - *(int *)e2;
}
int cmp_by_name(const void *e1, const void *e2)
{
return strcmp(((struct s*)e1)->name, ((struct s*)e2)->name);
}
int cmp_by_age(const void *e1, const void *e2)
{
return ((struct s*)e1)->age-((struct s*)e2)->age;
}
void Swap(char *s1, char *s2,int width)
{
int i = 0;
for (i = 0; i < width;i++)
{
char tmp = *(s1 + i);
*(s1 + i) = *(s2 + i);
*(s2 + i) = tmp;
}
}
void BubbleSort(void *arr, int sz, int width,int (*cmp)(const void *e1,const void *e2) )
{
int i = 0;
int j = 0;
for (i = 0; i < sz - 1; i++)
{
for (j = 0; j < sz - 1 - i; j++)
{
if (cmp((char*)arr+width*j,(char *)arr+width*(j+1))>0)
{
Swap((char*)arr + width*j, (char *)arr + width*(j + 1), width);
}
}
}
}
int main()
{
int arr[] = { 2, 1, 0, 9, 8, 7, 5, 6, 4, 3 };
struct s stu[3] = { {"zhang",20}, {"hushu",90}, {"wangwang",30} };
int sz = sizeof(arr) / sizeof(arr[0]);
int sz2 = sizeof(stu) / sizeof(stu[0]);
//BubbleSort(arr, sz, sizeof(arr[0]), cmp_int);
//按名字从小到大排序
BubbleSort(stu, sz2, sizeof(stu[0]), cmp_by_name);
//按年龄排
BubbleSort(stu, sz2, sizeof(stu[0]), cmp_by_age);
system("pause");
return 0;
}