Last active
January 2, 2016 17:19
-
-
Save Zegis/8335858 to your computer and use it in GitHub Desktop.
Void* arithmetics example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<cstring> | |
using namespace std; | |
int sortAscending(const void* A, const void* B); | |
int sourtDouble(const void* A, const void* B); | |
void bubbleSort(void * base, size_t num, size_t size, int (*compare)(const void*, const void*)); | |
int main(int argc, char* argv[]) | |
{ | |
int values [] = { 88, 56, 100, 2, 25 }; | |
for(int i=0; i < 5; ++i) | |
cout << *(values + i) << " "; | |
cout << endl; | |
bubbleSort(values, 5, sizeof(int), sortAscending); | |
for(int i=0; i < 5; ++i) | |
cout << *(values + i) << " "; | |
cin.get(); | |
double val[] = { 88.5 , 56.2, 100.02, 2.1, 25.9}; | |
for(int i=0; i<5; ++i) | |
cout << *(val+i) << " "; | |
cout << endl; | |
bubbleSort(val, 5, sizeof(double), sourtDouble); | |
for(int i=0; i<5; ++i) | |
cout << *(val+i) << " "; | |
return 0; | |
} | |
int sortAscending(const void * A, const void * B) | |
{ | |
if( *((int*)A) > *((int*)B)) return 1; | |
if( *((int*)A) < *((int*)B)) return -1; | |
return 0; | |
} | |
int sourtDouble(const void *A, const void *B) | |
{ | |
cout << "Comparer has: " << *((double*)A) << " " <<*((double*)B) << endl ; | |
if( *((double*)A) > *((double*)B)) return 1; | |
if( *((double*)A) < *((double*)B)) return -1; | |
return 0; | |
} | |
void bubbleSort(void * base, size_t num, size_t size, int (*compare)(const void*, const void*)) | |
{ | |
void* A; | |
void* B; | |
void* tmp = malloc(size); | |
int n = num; | |
do{ | |
for(int i=0; i < n-1; ++i) | |
{ | |
A = static_cast<char*>(base) + i*size; | |
B = static_cast<char*>(base) + (i+1)*size; | |
if( compare( A, B) == 1) | |
{ | |
//Swap | |
memset(tmp,0,size); | |
memcpy (tmp, A, size); | |
memcpy (A, B, size); | |
memcpy (B, tmp, size); | |
} | |
} | |
--n; | |
}while(n > 1); | |
free(tmp); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment