-
Notifications
You must be signed in to change notification settings - Fork 0
/
59_merge_sort.c
63 lines (60 loc) · 1.65 KB
/
59_merge_sort.c
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
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<stdio.h>
void printArray(int *a, int n){//prints the array
for(int i = 0;i<n;i++){
printf("%d ",a[i]);
}
printf("\n");
}
void swap(int *a , int*b)// used for swaping with call by referernce
{ int temp = *a;
*a = *b;
*b = temp;
}
void merge(int *a, int mid, int low, int high){
int i,j,k,b[100];
i = k = low;
j = mid +1;
while(i<=mid&&j<=high){ //to insert the sortest element into b
if (a[i]<a[j]){
b[k] = a[i];
i++;
k++; }
else {
b[k] = a[j];
k++;
j++;
}}
//inserting the left over elements into b
while(i<=mid){
b[k] = a[i];
i++;
k++;
}
//inserting the left over elements into b
while(j<=high){
b[k] = a[j];
j++;
k++; }
//copying into a again
for(int l = low;l<=high;l++){//as b also started entry from k = mid not from the zero index
a[l] = b[l];
}
}
// high is ind
void mergesort(int *a,int low,int high){ //recursive programe for merging
int mid;
if (low<high){ // means atleast the array should cotain two elements
mid = (low+high)/2; // gives an integer value only no .5
mergesort(a,low,mid); // again applying mergesort two bifurcated array
mergesort(a,mid+1,high);
merge(a,mid,low,high);//merging them both
}}
int main(){
int a[] = {3,5,2,13,37,12,34,99,15,14,43,37};
int size = sizeof(a)/sizeof(a[0]); //lenght of the array
printf("the size of array is %d\n",size);
printArray(a,size);
mergesort(a,0,size-1);//applying merge sort
printArray(a,size);
return 0;
}