Skip to content

Instantly share code, notes, and snippets.

@Transfusion
Created October 19, 2014 03:18
Show Gist options
  • Save Transfusion/f6325de064ae9288d6cc to your computer and use it in GitHub Desktop.
Save Transfusion/f6325de064ae9288d6cc to your computer and use it in GitHub Desktop.
mergesort_in_c
#include <stdio.h>
#include <stdlib.h>
void mergeSortedLists(int a[], int b[], int c[], int sizeofa, int sizeofb){
//int sizeofa = sizeof(a)/sizeof(int);
int indexa = 0, indexb = 0, indexc = 0;
//int sizeofb = sizeof(b)/sizeof(int);
int sizeofc = sizeofa + sizeofb;
printf("%d\n", sizeofc);
while (indexa < sizeofa && indexb < sizeofb){
if(a[indexa] < b[indexb]){
c[indexc] = a[indexa];
indexa++;
}
else {
c[indexc] = b[indexb];
indexb++;
}
indexc++;
}
while (indexa < sizeofa){
//printf("Ended list\n");
c[indexc]=a[indexa];
indexa++;indexc++;
}
while (indexb < sizeofb){
//printf("Ended list\n");
c[indexc] = b[indexb];
indexb++;indexc++;
}
}
void sort(int array[], int size){
int *A1, *A2;
int n1, n2;
if (size < 2){
return;
}
n1 = size/2;
n2 = size-n1;
A1 = (int*)malloc(sizeof(int) * n1);
A2 = (int*)malloc(sizeof(int) * n2);
int i;
/* move the first n/2 elements to A1 */
for (i = 0; i < n1; i++) {
A1[i] = array[i];
}
for (i = 0; i < n2; i++) {
A2[i] = array[i+n1];
}
sort(A1, n1);
sort(A2, n2);
/* merge the result of a recursion */
mergeSortedLists(A1, A2, array, n1, n2);
free(A1);
free(A2);
}
int main(int argc, char *argv[]){
/*int sortedarray1[] = {1,5,9,10,20};
int sortedarray2[] = {2,2,3,4,5,9,10,11,20};
int len1 = sizeof(sortedarray1)/sizeof(int);
int len2 = sizeof(sortedarray2)/sizeof(int);
int sortedlistlength = len1+len2;
int resultingarray[sortedlistlength];
mergeSortedLists(sortedarray1,sortedarray2,resultingarray, len1, len2);*/
int testarray[] = {4,23,2391,29,329};
int sortedlistlength = sizeof(testarray)/sizeof(int);
sort(testarray, sortedlistlength);
//printf("%d\n", sortedlistlength);
int i;
for (i=0;i<sortedlistlength;i++){
printf("%d ", testarray[i]);
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment