Created
May 1, 2016 12:33
-
-
Save sekrasoft/4ecadd433e967fb8023ee5a72e84e42c to your computer and use it in GitHub Desktop.
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 <stdio.h> | |
#include <stdlib.h> | |
void swap(void* a, void* b, size_t size) { | |
char tmp; | |
for(size_t i = 0; i < size; ++i) { | |
tmp = ((char*)a)[i]; | |
((char*)a)[i] = ((char*)b)[i]; | |
((char*)b)[i] = tmp; | |
} | |
} | |
void random_sort (void* base, size_t num, size_t size, int (*compar)(const void*,const void*)) { | |
int sorted; | |
do { | |
for(int i=1; i<num; ++i) | |
if(rand() > RAND_MAX >> 1) | |
swap(base + size * (i - 1), base + size * i, size); | |
sorted = 1; | |
for(int i=1; i<num; ++i) | |
if(compar(base + size * (i - 1), base + size * i) < 0) { | |
sorted = 0; | |
break; | |
} | |
} while(!sorted); | |
} | |
int compare_float(const void* a, const void* b) { | |
if(*(const float*)a > *(const float*)b) return -1; | |
if(*(const float*)a < *(const float*)b) return +1; | |
return 0; | |
} | |
int main(void) { | |
float array[3] = {2.8, -4.5, 0.0}; | |
random_sort(array, 3, sizeof(float), compare_float); | |
printf("%f %f %f", array[0], array[1], array[2]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Вывод программы: