Skip to main content

Merge Sort Implementation

*
#include<iostream> #include<cstdio> using namespace std; void merging(int arr[],int startPoint, int midPoint, int endPoint) { int firstArrCnt,secArrCnt,i,temp[endPoint]; firstArrCnt = startPoint; secArrCnt = midPoint + 1; for(i = firstArrCnt; firstArrCnt<=midPoint && secArrCnt<=endPoint; i++) { if(arr[firstArrCnt] < arr[secArrCnt]) temp[i] = arr[firstArrCnt++]; else temp[i] = arr[secArrCnt++]; } while(firstArrCnt <= midPoint) temp[i++] = arr[firstArrCnt++]; while(secArrCnt <= endPoint) temp[i++] = arr[secArrCnt++]; for(i = startPoint; i<=endPoint; i++) arr[i] = temp[i]; } void sorting(int arr[],int startPoint, int endPoint) { int midPoint; if(startPoint >= endPoint) { return; } else { midPoint = (startPoint+endPoint)/2; sorting(arr,startPoint, midPoint); sorting(arr,midPoint+1, endPoint); merging(arr,startPoint, midPoint, endPoint); } } int main() { int i, n; printf("Enter number of elements:\n"); scanf("%d", &n); int arr[n]; printf("Enter %d elements:\n",n); for(i=1; i<=n; i++) scanf("%d", &arr[i]); sorting(arr,1, n); printf("\nAfter sorting the Array:\n"); for(i = 1; i<=n; i++) printf("%d ", arr[i]); puts(""); return 0; }

Quote: All our dreams can come true, if we have the courage to pursue them...|| It always seems impossible until it's done || Failure will never overtake me if my determination to succeed is strong enough. || Believe in yourself. You are braver than you think, more talented than you know, and capable of more than you imagine...|| Believe in yourself, take on your challenges, dig deep within yourself to conquer fears. Never let anyone bring you down. You got to keep going...||