Advertisement
Futaikhi

Modul 4 [Struktur Data]

May 2nd, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int nilai[5];
  6.  
  7. void combine(int a[ ],int p,int q,int r)
  8. {
  9.     int c[5];
  10.     int i = p;
  11.     int j = q+1;
  12.     int k = p;
  13.     while((i<=q) && (j<=r))
  14.     {
  15.         if (a[i]<a[j])
  16.         {
  17.             c[k] = a[i];
  18.             i=i+1;
  19.             k=k+1;
  20.         }
  21.         else
  22.         {
  23.             c[k] = a[j];
  24.             j=j+1;
  25.             k=k+1;
  26.         }
  27.     }
  28.     while(i<=q)
  29.     {
  30.         c[k] = a[i];
  31.         i=i+1;
  32.         k=k+1;
  33.     }
  34.     while(j<=r)
  35.     {
  36.         c[k] = a[j];
  37.         j=j+1;
  38.         k=k+1;
  39.     }
  40.     int l=p;
  41.     while(l<=r)
  42.     {
  43.         a[l] = c[l];
  44.         l=l+1;
  45.     }
  46. }
  47.  
  48. void mergesort(int a[ ],int low,int high)
  49. {
  50.     int mid;
  51.     if (low<high)
  52.     {
  53.         mid=(low+high)/2;
  54.         mergesort(a,low,mid);
  55.         mergesort(a,mid+1,high);
  56.         combine(a,low,mid,high);
  57.     }
  58. }
  59.  
  60. int main()
  61. {
  62.     cout<<"\t\t--||CONTOH PROGRAM MERGE SORT||--"<<endl;
  63.     cout<<"enter the elements"<<endl;
  64.     for(int i=0 ; i<5 ;i++)
  65.     {
  66.         cin>>nilai[i];
  67.     }
  68.     mergesort(nilai,0,4);
  69.     cout<<"sorted array"<<endl;
  70.     for(int i=0 ; i<5 ; i++)
  71.     {
  72.         cout<<nilai[i]<<", ";
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement