forked from jvm-coder/Hacktoberfest2022_aakash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge Sort.c
More file actions
50 lines (50 loc) · 1020 Bytes
/
Merge Sort.c
File metadata and controls
50 lines (50 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<stdio.h>
void Merge(int arr[], int low, int mid, int high){
int temp1, temp2, i, j, k=low;
temp1=mid-low+1;
temp2=high-mid;
int arr1[temp1], arr2[temp2];
for(i=0;i<temp1;i++)
arr1[i]=arr[i+low];
for(j=0;j<temp2;j++)
arr2[j]=arr[mid+j+1];
i=0;
j=0;
while(i<temp1 && j<temp2){
if(arr1[i]<=arr2[j]){
arr[k]=arr1[i];
i++;
}
else{
arr[k]=arr2[j];
j++;
}
k++;
}
for(;i<temp1;i++)
arr[k++]=arr1[i];
for(;j<temp2;j++)
arr[k++]=arr2[j];
}
void MergeSort(int arr[], int low, int high){
if(low>=high)
return;
int mid=(low+high)/2;
MergeSort(arr,low,mid);
MergeSort(arr,mid+1,high);
Merge(arr,low,mid,high);
}
void main(){
int size, i;
printf("Enter the size of array: ");
scanf("%d",&size);
int arr[size];
printf("Enter array elements in unsorted order:");
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
MergeSort(arr,0,size-1);
printf("Sorted array: ");
for(i=0;i<size;i++){
printf("%d ",arr[i]);
}
}