Advertisement
huyhung94

Giải thuật Merge Sort

Oct 6th, 2013
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.00 KB | None | 0 0
  1. program MergeSort;
  2. procedure Merge(X,b,m,n,Z);
  3.     begin
  4.         i:=b; j:=m+1; k:=b;
  5.         while((i<=m) and (j<=n)) do
  6.             begin
  7.                 if a[i]<a[j] then
  8.                     begin
  9.                         z[k]:=a[i]; inc(i);
  10.                     end
  11.                 else
  12.                     begin
  13.                         z[k]::=a[i]; inc(j);
  14.                     end;
  15.                 inc(k);
  16.             end;
  17.         if i>m then {Mạch 1 hết phần tử}
  18.             (Z[k]....Z[n]):=(X[j]...X[n])
  19.     End;
  20.  
  21. Procedure M_Pass(X,Y,l);
  22.     begin
  23.         i:=1;
  24.         while(i+2*l-1<=n) do {Còn đủ 2 mạch có độ dài bằng nhau}
  25.             begin
  26.                 Merge(X,i,i+l-1,i+2*l-1,Y);
  27.                 i:=i+2*l;    {Hòa nhập hai mạch tiếp theo}
  28.             end;
  29.         if (i+l<=n) then    {Còn hai mạch nưhng mạch cuối không đủ độ dài}
  30.             Merge(X,i,i+l-1,n,Y)
  31.         else
  32.             (Y[i],...Y[n])=(X[i],...X[n]);
  33.     End;
  34.    
  35. Procedure Merge_Sort(X,n);
  36.     Begin
  37.         l:=1;
  38.         while l<n do
  39.             begin
  40.                 M_Pass(X,Y,l,n);
  41.                 l:=l*2;
  42.                 M_Pass(Y,X,l,n);
  43.                 l:=l*2;
  44.             end;
  45.     End;
  46. BEGIN
  47.     Nhập n;
  48.     Nhập các phần tử Xi;
  49.     Merge_Sort(X,n);
  50.     In danh sách đã sắp xếp;
  51.     readln
  52. END:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement