Skip to content

Instantly share code, notes, and snippets.

@erictt erictt/MergeSort.c
Last active Oct 22, 2018

Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void myMergeSort(int arr[], int size);
void printarr(int arr[], int length);
void mergeBothSide(int arr[], int leftarr[], int rightarr[], int halfLen, int rightHalfLen);
int main(void)
{
int arr[] = {6, 5, 3, 1, 8, 7, 2, 4};
int length = 8;
printf("Original: ");
printarr(arr, length);
myMergeSort(arr, length);
printf("END Merged: ");
printarr(arr, length);
}
void mymergesort(int arr[], int size)
{
if(size <= 1) return;
int halfLen = ceil(size / 2);
int leftarr[halfLen];
int rightHalfLen = size - halfLen;
int rightarr[rightHalfLen];
myMergeSort(leftarr, halfLen);
myMergeSort(rightarr, rightHalfLen);
mergeBothSide(arr, leftarr, rightarr, halfLen, rightHalfLen);
}
void mergeBothSide(int arr[], int leftarr[], int rightarr[], int leftHalfLen, int rightHalfLen)
{
int length = leftHalfLen + rightHalfLen;
int leftIndex = 0, rightIndex = 0;
for(int i = 0; i < length; i++)
{
if(rightIndex >= rightHalfLen) {
arr[i] = leftarr[leftIndex];
leftIndex++;
} else if(leftIndex >= leftHalfLen) {
arr[i] = rightarr[rightIndex];
rightIndex++;
} else if(leftarr[leftIndex] <= rightarr[rightIndex]) {
arr[i] = leftarr[leftIndex];
leftIndex++;
} else {
arr[i] = rightarr[rightIndex];
rightIndex++;
}
}
}
void printarr(int arr[], int length) {
printf("Print ARR: ");
for(int i = 0; i < length; i ++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.