Last active
August 29, 2015 14:02
-
-
Save Prince781/4f635e11f39b69568c07 to your computer and use it in GitHub Desktop.
Simple merge sort
This file contains hidden or 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> | |
| #include <time.h> | |
| #include <string.h> | |
| #define sz 100 | |
| void msort(int *out, int *begin, int *end); | |
| static void merge(int *out, int *lbeg, int *lend, int *rend); | |
| void printr(int *arr, int *end); | |
| void rfillr(int *arr, int *end); | |
| int cmp(const void *a, const void *b); | |
| int main(int argc, char *argv[]) | |
| { | |
| int sorted_r[sz]; | |
| int r[sz]; | |
| rfillr(r, r+sz); | |
| printf("Array (unsorted): \n\t"); | |
| printr(r, r+sz); | |
| printf("\n"); | |
| msort(sorted_r, r, r+sz); | |
| printf("Array (sorted): \n\t"); | |
| printr(sorted_r, sorted_r+sz); | |
| printf("\n"); | |
| printf("qsort: \n\t"); | |
| qsort(r, sz, sizeof(int), cmp); | |
| printr(r, r+sz); | |
| printf("\n"); | |
| if (memcmp(sorted_r, r, sz*sizeof(int)) == 0) | |
| printf("array is sorted\n"); | |
| else | |
| printf("array is not sorted\n"); | |
| return 0; | |
| } | |
| int cmp(const void *a, const void *b) | |
| { | |
| return *(const int *)a > *(const int *)b; | |
| } | |
| void printr(int *arr, int *end) | |
| { | |
| for (; arr < end; ++arr) | |
| printf("%d ", *arr); | |
| } | |
| void rfillr(int *arr, int *end) | |
| { | |
| int len; | |
| srand(time(NULL)); | |
| for (len=(end-arr)*3; arr < end; ) | |
| *arr++ = rand() % len; | |
| } | |
| void msort(int *out, int *begin, int *end) | |
| { | |
| int *c = begin + (end-begin)/2; | |
| if (end - begin > 2) { | |
| msort(out, begin, c); | |
| msort(out+(c-begin), c, end); | |
| } | |
| merge(out, begin, c, end); | |
| } | |
| static void merge(int *out, int *lbeg, int *lend, int *rend) | |
| { | |
| int *rbeg, *begin, *end, *bout; | |
| begin=lbeg; | |
| end=rend; | |
| bout=out; | |
| for (rbeg = lend; lbeg < lend || rbeg < rend;) | |
| if (lbeg < lend && (rbeg == rend || *lbeg < *rbeg)) | |
| *out++ = *lbeg++; | |
| else | |
| *out++ = *rbeg++; | |
| memcpy(begin, bout, (end-begin)*sizeof(int)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment