for (int *cur = begin + 1; cur < end; ++cur) {
int tmp = *cur;
int *pos = cur;
for (int *i = cur; i > begin && *(i - 1) > tmp; --i) {
*i = *(i - 1);
pos = i - 1;
}
*pos = tmp;
}
}
void insertion_sort_2(int *begin, int *end) {
for (int *cur = begin + 1; cur < end; ++cur) {
int tmp = *cur;
int *i = cur;
for (; i > begin && *(i - 1) > tmp; --i) {
*i = *(i - 1);
}
*(i-1) = tmp;
}
}
I initially thought the second insertion sort algorithm is faster,but after the experiment it was found that the second insertion sort algorithm is slower!
Result:
algorithm
run time
insertion_sort_1
2245 ms
insertion_sort_2
2899 ms
Test code:
#include
#include
#include
#include
#define SMALL_N 5000
#define MIDDLE_N 100000
#define BIG_N 10000000
__attribute__((constructor))
void __init__Rand__() {
srand(time(0));
}
bool check(int* begin, int* end) {
int* cur = begin;
for(; cur < end - 1; ++cur) {
if(*cur > *(cur + 1)) return false;
}
return true;
}
#define TEST(func, begin, end){\
printf("Test %s : ", #func);\
int *tmp = (int*)malloc(sizeof(int) * (end - begin));\
memcpy(tmp, begin, sizeof(int) * (end - begin));\
long long b = clock();\
func(tmp, tmp - end + begin);\
long long e = clock();\
if(check(tmp, tmp - end + begin)) printf("\tOK");\
else printf("\tWrong");\
printf("\t%lld ms\n", (e - b) * 1000 / CLOCKS_PER_SEC);\
free(tmp);\
}
int *geneArr(unsigned n) {
int* arr = (int*)malloc(sizeof(int) * n);
for(int i = 0; i < n; ++i) {
int tmp = rand() % 10000;
arr[i] = tmp;
}
return arr;
}
void swap(int* a, int* b) {
if(a == b) return;
int c = *a;
*a = *b;
*b = c;
}
// ================================================================================================
void selection_sort(int* begin,int* end) {
for(int* cur = begin; cur < end - 1; ++cur) {
int* minimum = cur;
for(int* cur_find = cur + 1; cur_find != end; ++cur_find) {
if(*cur_find < *minimum) minimum = cur_find;
}
if(minimum != cur) swap(minimum, cur);
}
}
void insertion_sort_1(int *begin, int *end) {
for (int *cur = begin + 1; cur < end; ++cur) {
int tmp = *cur;
int *pos = cur;
for (int *i = cur; i > begin && *(i - 1) > tmp; --i) {
*i = *(i - 1);
pos = i - 1;
}
*pos = tmp;
}
}
void insertion_sort_2(int *begin, int *end) {
for (int *cur = begin + 1; cur < end; ++cur) {
int tmp = *cur;
int *i = cur;
for (; i > begin && *(i - 1) > tmp; --i) {
*i = *(i - 1);
}
*(i-1) = tmp;
}
}
int main() {
// int N=SMALL_N;
int N=MIDDLE_N;
// int N=BIG_N;
int* arr = geneArr(N);
TEST(insertion_sort_1, arr, arr + N);
TEST(insertion_sort_2, arr, arr + N);
free(arr);
return 0;
}
In the second algorithm,I have reduce the assignment operator,but it becomes slower.I want to know why?Thanks!
0 comments:
Post a Comment
Thanks