Skip to content

Instantly share code, notes, and snippets.

@r4j0x00
Created October 8, 2020 19:01
Show Gist options
  • Save r4j0x00/bd231a424778f5fc579484c287bb1148 to your computer and use it in GitHub Desktop.
Save r4j0x00/bd231a424778f5fc579484c287bb1148 to your computer and use it in GitHub Desktop.
MergeSort recursive
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIZE 0x10000
#define Type int64_t
#define printArray(arr, size) printf("["); \
for(int z=0;z<size;++z) { \
if(z != size-1) \
printf("%lli, ", arr[z]); \
else \
printf("%lli]\n", arr[z]); \
}
void mergeSort(Type * Array, size_t size) {
if (size < 2) return;
size_t lsize = size/2;
mergeSort(Array, lsize);
mergeSort(&Array[lsize], size-lsize);
Type * temp = (Type *)malloc(size * sizeof(Type));
uint64_t i, j;
i = 0, j = lsize;
uint64_t cur = 0;
while(i < lsize && j < size) {
if(Array[i] < Array[j])
temp[cur++] = Array[i++];
else
temp[cur++] = Array[j++];
}
while(i < lsize)
temp[cur++] = Array[i++];
while(j < size)
temp[cur++] = Array[j++];
for(i=0; i<size; ++i)
Array[i] = temp[i];
free(temp);
}
int main(void) {
Type * arr = (Type *)malloc(SIZE * sizeof(Type));
srand(time(NULL));
for(uint64_t i=0; i<SIZE; ++i)
arr[i] = rand();
mergeSort(arr, SIZE);
printArray(arr, SIZE);
free(arr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment