-
-
Save DWD3/cab005e4f2d36761b9f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
void MergeSort(int *A,int length); | |
void intswap(int*a,int* b); | |
void Merge(int *A,int *L,int leftCount,int *R,int rightCount); | |
int main(void) | |
{ | |
int i; | |
int j=0; | |
int k; | |
int A[20]; | |
while(scanf("%d",&i)==1) | |
{ | |
A[j]=i; | |
j++; | |
} | |
k=j; | |
MergeSort(A,k); | |
printf("the number you entered is : \n"); | |
for(j=0;j<k;j++) | |
{ | |
printf("%d\n",A[j]); | |
} | |
return 0; | |
} | |
void MergeSort(int *A,int n) { | |
int mid,i, *L, *R; | |
if(n < 2) return; // base condition. If the array has less than two element, do nothing. | |
mid = n/2; // find the mid index. | |
// create left and right subarrays | |
// mid elements (from index 0 till mid-1) should be part of left sub-array | |
// and (n-mid) elements (from mid to n-1) will be part of right sub-array | |
L = (int*)malloc(mid*sizeof(int)); | |
R = (int*)malloc((n- mid)*sizeof(int)); | |
for(i = 0;i<mid;i++) L[i] = A[i]; // creating left subarray | |
for(i = mid;i<n;i++) R[i-mid] = A[i]; // creating right subarray | |
MergeSort(L,mid); // sorting the left subarray | |
MergeSort(R,n-mid); // sorting the right subarray | |
Merge(A,L,mid,R,n-mid); // Merging L and R into A as sorted list. | |
free(L); | |
free(R); | |
} | |
void Merge(int *A,int *L,int leftCount,int *R,int rightCount) { | |
int i,j,k; | |
// i - to mark the index of left aubarray (L) | |
// j - to mark the index of right sub-raay (R) | |
// k - to mark the index of merged subarray (A) | |
i = 0; j = 0; k =0; | |
while(i<leftCount && j< rightCount) { | |
if(L[i] < R[j]) A[k++] = L[i++]; | |
else A[k++] = R[j++]; | |
} | |
while(i < leftCount) A[k++] = L[i++]; | |
while(j < rightCount) A[k++] = R[j++]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment