Last active
September 2, 2023 01:45
-
-
Save ChenZhongPu/a011b2ec7c011e208e0018f4be0b899e to your computer and use it in GitHub Desktop.
blogs-2023-09
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
// simple code to benchmark the sort | |
long time_it(void (*f)(int *, int), int *arr, int n) { | |
struct timespec start, end; | |
clock_gettime(CLOCK_MONOTONIC, &start); | |
f(arr, n); | |
clock_gettime(CLOCK_MONOTONIC, &end); | |
long diff = (end.tv_sec - start.tv_sec) * 1e9; | |
diff += (end.tv_nsec - start.tv_nsec); | |
return diff; | |
} |
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 <stdlib.h> | |
#include <string.h> | |
#define CUT_OFF 128 | |
void exch(int *a, int i, int j) { | |
int swap = a[i]; | |
a[i] = a[j]; | |
a[j] = swap; | |
} | |
void insertion_sort(int *arr, int lo, int hi) { | |
for (int i = lo + 1; i <= hi; i++) { | |
for (int j = i; j > lo && arr[j] < arr[j - 1]; j--) { | |
exch(arr, j, j - 1); | |
} | |
} | |
} | |
void merge(int *src, int *dst, int lo, int mid, int hi) { | |
int i = lo, j = mid + 1; | |
for (int k = lo; k <= hi; k++) { | |
if (i > mid) { | |
dst[k] = src[j++]; | |
} else if (j > hi) { | |
dst[k] = src[i++]; | |
} else if (src[j] < src[i]) { | |
dst[k] = src[j++]; | |
} else { | |
dst[k] = src[i++]; | |
} | |
} | |
} | |
void merge_sort(int *src, int *dst, int lo, int hi) { | |
if (hi <= lo + CUT_OFF) { | |
insertion_sort(dst, lo, hi); | |
return; | |
} | |
int mid = lo + (hi - lo) / 2; | |
merge_sort(dst, src, lo, mid); | |
merge_sort(dst, src, mid + 1, hi); | |
if (src[mid] <= src[mid + 1]) { | |
memcpy(dst + lo, src + lo, (hi - lo + 1) * sizeof(int)); | |
return; | |
} | |
merge(src, dst, lo, mid, hi); | |
} | |
void xsort(int *arr, int len) { | |
int *aux = malloc(len * sizeof(int)); | |
memcpy(aux, arr, len * sizeof(int)); | |
merge_sort(aux, arr, 0, len - 1); | |
free(aux); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment