backlog

Merge Sort

Mar 19th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. /* C program for Merge Sort */
  2. #include<stdlib.h>
  3. #include<stdio.h>
  4.  
  5. // Merges two subarrays of arr[].
  6. // First subarray is arr[l..m]
  7. // Second subarray is arr[m+1..r]
  8. void merge(int arr[], int l, int m, int r)
  9. {
  10.     int i, j, k;
  11.     int n1 = m - l + 1;
  12.     int n2 =  r - m;
  13.  
  14.     /* create temp arrays */
  15.     int L[n1], R[n2];
  16.  
  17.     /* Copy data to temp arrays L[] and R[] */
  18.     for (i = 0; i < n1; i++)
  19.         L[i] = arr[l + i];
  20.     for (j = 0; j < n2; j++)
  21.         R[j] = arr[m + 1+ j];
  22.  
  23.     /* Merge the temp arrays back into arr[l..r]*/
  24.     i = 0; // Initial index of first subarray
  25.     j = 0; // Initial index of second subarray
  26.     k = l; // Initial index of merged subarray
  27.     while (i < n1 && j < n2)
  28.     {
  29.         if (L[i] <= R[j])
  30.         {
  31.             arr[k] = L[i];
  32.             i++;
  33.         }
  34.         else
  35.         {
  36.             arr[k] = R[j];
  37.             j++;
  38.         }
  39.         k++;
  40.     }
  41.  
  42.     /* Copy the remaining elements of L[], if there
  43.        are any */
  44.     while (i < n1)
  45.     {
  46.         arr[k] = L[i];
  47.         i++;
  48.         k++;
  49.     }
  50.  
  51.     /* Copy the remaining elements of R[], if there
  52.        are any */
  53.     while (j < n2)
  54.     {
  55.         arr[k] = R[j];
  56.         j++;
  57.         k++;
  58.     }
  59. }
  60.  
  61. /* l is for left index and r is right index of the
  62.    sub-array of arr to be sorted */
  63. void mergeSort(int arr[], int l, int r)
  64. {
  65.     if (l < r)
  66.     {
  67.         // Same as (l+r)/2, but avoids overflow for
  68.         // large l and h
  69.         int m = l+(r-l)/2;
  70.  
  71.         // Sort first and second halves
  72.         mergeSort(arr, l, m);
  73.         mergeSort(arr, m+1, r);
  74.  
  75.         merge(arr, l, m, r);
  76.     }
  77. }
  78.  
  79. /* UTILITY FUNCTIONS */
  80. /* Function to print an array */
  81. void printArray(int A[], int size)
  82. {
  83.     int i;
  84.     for (i=0; i < size; i++)
  85.         printf("%d ", A[i]);
  86.     printf("\n");
  87. }
  88.  
  89. /* Driver program to test above functions */
  90. int main()
  91. {
  92.     int arr[] = {12, 11, 13, 5, 6, 7};
  93.     int arr_size = sizeof(arr)/sizeof(arr[0]);
  94.  
  95.     printf("Given array is \n");
  96.     printArray(arr, arr_size);
  97.  
  98.     mergeSort(arr, 0, arr_size - 1);
  99.  
  100.     printf("\nSorted array is \n");
  101.     printArray(arr, arr_size);
  102.     return 0;
  103. }
Add Comment
Please, Sign In to add comment