The following code shows an Implementation of Merge Sort in C Language.
// Implementation of Merge Sort in C
#include <stdio.h>
void Merge(int myarray[], int first, int last, int middle);
void MergeSort(int myarray[], int first, int last)
{
int middle;
if(first<last)
{
middle=(first+last)/2;
MergeSort(myarray, first, middle);
MergeSort(myarray, middle+1, last);
Merge(myarray, first, last, middle);
}
else
{
return;
}
}
void Merge(int myarray[], int first, int last, int middle)
{
int size1, size2, i, i1, i2, i3;
size1=1+middle-first;
size2=last-middle;
int first_array[size1], second_array[size2];
for(i=0;i<size1;i++)
{
first_array[i]=myarray[first+i];
}
for(i=0;i<size2;i++)
{
second_array[i]=myarray[1+i+middle];
}
i1=i2=0;
i3=first;
while((i1<size1) && (i2<size2))
{
if(first_array[i1]<second_array[i2])
{
myarray[i3]=first_array[i1];
i1++;
}
else
{
myarray[i3]=second_array[i2];
i2++;
}
i3++;
}
while(i1<size1)
{
myarray[i3]=first_array[i1];
i1++;
i3++;
}
while(i2<size2)
{
myarray[i3]=second_array[i2];
i2++;
i3++;
}
}
int main()
{
int i, j, elements_count;
int myarray[]={8, 12, -9, 30, 29, -80, 55, 62, 83, 44, -12, 6, 15};
elements_count=sizeof(myarray)/sizeof(int);
printf("Original Array....\n");
for(i=0;i<elements_count;i++)
printf("%d ", myarray[i]);
printf("\n\n");
MergeSort(myarray, 0, elements_count);
printf("Sorted Array....\n");
for(i=0;i<elements_count;i++)
printf("%d ", myarray[i]);
printf("\n\n");
return 0;
}
Output
Further Reading
50+ C Programming Interview Questions and Answers
C Program to Find Factorial of a Number
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML