#include
#include
#include
void print_arr(int arr[],int n);
void msort(int arr[] , int tempArr[] , int left , int right);
void merge(int arr[],int tempArr[],int left,int mid,int right);
void merge_sort(int arr[] , int n);
void print_arr(int arr[],int n)
{
for(int i = 0 ; i < n ; i++){
printf("%4d",arr[i]);
}
putchar('\n');
}
void msort(int arr[] , int tempArr[] , int left , int right)
{
if(left < right){
int mid = (left + right)/2;
msort(arr,tempArr,left,mid);
msort(arr,tempArr,mid+1,right);
merge(arr,tempArr,left,mid,right);
}
}
void merge_sort(int arr[] , int n)
{
int *tempArr = (int *)malloc(n * sizeof(int));
if(tempArr){
msort(arr,tempArr,0,n-1);
free(tempArr);
}else{
printf("error:failed to allocate memory");
}
}
void merge(int arr[],int tempArr[],int left,int mid,int right)
{
int l_pos = left;
int r_pos = mid+1;
int pos = left;
while(l_pos <= mid && r_pos <= right){
if(arr[l_pos] < arr[r_pos]){
tempArr[pos++] = arr[l_pos++];
}else{
tempArr[pos++] = arr[r_pos++];
}
}
while(l_pos <= mid){
tempArr[pos++] = arr[l_pos++];
}
while(r_pos <= right){
tempArr[pos++] = arr[r_pos++];
}
while(left <= right){
arr[left] = tempArr[left];
left++;
}
}
int main()
{
int arr[] = {9,5,2,7,12,4,3,1,11};
int n = 9;
print_arr(arr,n);
merge_sort(arr,n);
print_arr(arr,n);
return 0;
}
- 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
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81