Skip to content
This repository has been archived by the owner on Oct 14, 2021. It is now read-only.

Merge sort algorithm in c #557

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions Programming/C/MergeSort/MergeSort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#include <stdio.h>

// MergeSort by Khand

void printArray(int *A, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}

void merge(int A[], int mid, int low, int high)
{
int i, j, k, B[100];
i = low;
j = mid + 1;
k = low;

while (i <= mid && j <= high)
{
if (A[i] < A[j])
{
B[k] = A[i];
i++;
k++;
}
else
{
B[k] = A[j];
j++;
k++;
}
}
while (i <= mid)
{
B[k] = A[i];
k++;
i++;
}
while (j <= high)
{
B[k] = A[j];
k++;
j++;
}
for (int i = low; i <= high; i++)
{
A[i] = B[i];
}

}

void mergeSort(int A[], int low, int high){
int mid;
if(low<high){
mid = (low + high) /2;
mergeSort(A, low, mid);
mergeSort(A, mid+1, high);
merge(A, mid, low, high);
}
}

int main()
{
// int A[] = {9, 14, 4, 8, 7, 5, 6};
int A[] = {9, 1, 4, 14, 4, 15, 6};
int n = 7;

printf("\nArray given by Danish\n");
printArray(A, n);

printf("Welcome to Merge Sort\n");
mergeSort(A, 0, 6);
printArray(A, n);
return 0;
}