#include<stdio.h>
#include<Windows.h>
#include<string.h>
int cmp1(const void *x, const void *y)
{
return (*(int *)x) - (*(int *)y);
}
char cmp2(const void *x, const void *y)
{
return (*(char *)x) - (*(char*)y);
}
char *cmp3(const void *x, const void *y)
{
return strcmp(*(char **)x, *(char**)y);
}
void my_swap(void *p1, void *p2, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
char tmp = *((char *)p1 + i);
*((char *)p1 + i) = *((char *)p2 + i);
*((char *)p2 + i) = tmp;
}
}
void bubble(void *base, int count, int size, int(*cmp)(void *, void *))
{
int i = 0;
int j = 0;
for (i = 0; i < count - 1; i++)
{
for (j = 0; j < count - 1 - i; j++)
{
if (cmp((char *)base + j*size, (char *)base + (j+1)*size)>0)
{
my_swap((char *)base + j*size, (char *)base + (j + 1)*size, size);
}
}
}
}
int main()
{
int i;
int a1[10] = { 1, 5, 3, 2, 4, 7, 9, 6, 8 };
int sz1 = sizeof(a1) / sizeof(a1[0]);
bubble(a1, sz1, sizeof(int), cmp1);
for (i = 0; i < sz1; i++)
{
printf("%d ", a1[i]);
}
printf("\n");
char a2[5] = { 'a', 'e', 'c', 'b', 'd' };
int sz2 = sizeof(a2) / sizeof(a2[0]);
bubble(a2, sz2, sizeof(char ), cmp2);
for (i = 0; i < sz2; i++)
{
printf("%c ", a2[i]);
}
printf("\n");
char *a3[4] = { "aaaa", "bbbb", "cccc", "dddd" };
int sz3 = sizeof(a3) / sizeof(a3[0]);
bubble(a3, sz3, sizeof(char *), cmp3);
for (i = 0; i < sz3; i++)
{
printf("%s ", a3[i]);
}
printf("\n");
system("pause");
return 0;
}