Advertisement
Guest User

merge sort

a guest
May 30th, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include<iostream>
  2. usingnamespace std;
  3.  
  4. #define BrEl 20
  5.  
  6. void Merge(int Temp[], int Element[], constint list1, constint size1,
  7. constint list2, constint size2)
  8. {
  9.     int i = list1, j = list2, k = list1;
  10.  
  11.     while(i < list1 + size1 && j < list2 + size2)
  12.     {
  13.         if (Temp[i] < Temp[j])
  14.             Element[k++] = Temp[i++];
  15.         else
  16.             Element[k++] = Temp[j++];
  17.     }
  18.  
  19.     while (i < list1 + size1)  
  20.         Element[k++] = Temp[i++];
  21.     while (j < list2 + size2)  
  22.         Element[k++] = Temp[j++];
  23.     for (k = list1; k < list1 + size1 + size2; k++)  
  24.         Temp[k] = Element[k];
  25. }
  26.  
  27. void MergeSort(int Temp[], int Element[], constint list1, constint size)
  28. {
  29.     int list2, size1, size2;
  30.  
  31.     if (size > 1)
  32.     {
  33.         list2 = list1 + size / 2;
  34.         size1 = list2 - list1;
  35.         size2 = size - size1;
  36.         MergeSort(Temp, Element, list1, size1);
  37.         MergeSort(Temp, Element, list2, size2);
  38.         Merge(Temp, Element, list1, size1, list2, size2);
  39.     }
  40. }
  41.  
  42. int main()
  43. {
  44.     int
  45.         A[BrEl]={25,14,7,76,10,64,20,30,9,2,6,77,83,12,56,46,61,51,33,26};
  46.     int
  47.         B[BrEl]={25,14,7,76,10,64,20,30,9,2,6,77,83,12,56,46,61,51,33,26};
  48.  
  49.     cout<<"Unsorted array:"<<endl;
  50.     for(int i=0;i<BrEl;i++)
  51.     {
  52.         cout<<A[i]<<endl;
  53.     }
  54.     MergeSort(B,A,0,BrEl);
  55.     cout<<endl<<" Sorted array "<<endl;
  56.     for(int i=0;i<BrEl;i++)
  57.     {
  58.         cout<<B[i]<<endl;
  59.     }
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement