# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
Typedef char byte;
Typedef int (_ stdcall * comparefunction) (const byte *, const byte *);
Void _ stdcall bubblesort (byte * array, int size, int elem_size, comparefunction cmpfunc)
{
For (INT I = 0; I <size; I ++)
{
For (Int J = 0; j <size-1; j ++)
{
// Callback comparison Function
If (1 = (* cmpfunc) (array + J * elem_size, array + (J + 1) * elem_size ))
{
// Two elements are exchanged.
Byte * temp = new byte [elem_size];
Memcpy (temp, array + J * elem_size, elem_size );
Memcpy (array + J * elem_size, array + (J + 1) * elem_size, elem_size );
Memcpy (array + (J + 1) * elem_size, temp, elem_size );
Delete [] temp;
}
}
}
}
//////////////////////////////////////// //////////////////////////////////
// For the user, a callback function must be provided, and its address must be passed to the bubblesort () function. There are two simple examples below,
// One compares two integers and the other compares two strings:
Int _ stdcall compareints (const byte * velem1, const byte * velem2)
{
Int elem1 = * (int *) velem1;
Int elem2 = * (int *) velem2;
If (elem1 <elem2)
Return-1;
If (elem1> elem2)
Return 1;
Return 0;
}
Int _ stdcall comparestrings (const byte * velem1, const byte * velem2)
{
Const char * elem1 = (char *) velem1;
Const char * elem2 = (char *) velem2;
Return strcmp (elem1, elem2 );
}
//////////////////////////////////////// //////////////////////////////////
Int main (INT argc, char * argv [])
{
Int I;
Int array [] = {5432,432 1, 3210,210 9, 1098 };
Printf ("Before sorting ints with bubblesort: \ n ");
For (I = 0; I <5; I ++)
Printf ("% d", array [I]);
Bubblesort (byte *) array, 5, sizeof (array [0]), & compareints );
Printf ("\ nafter the sorting: \ n ");
For (I = 0; I <5; I ++)
Printf ("% d", array [I]);
Printf ("\ n ");
System ("pause ");
Return 0;
}