Recent

Author Topic: QuickSort  (Read 9121 times)

chanyawat

  • Newbie
  • Posts: 1
QuickSort
« on: February 28, 2016, 11:45:24 am »
Can someone help me? It´s a Quick Sort program. And there are still errors in this program. :(

Program Quicksort;

var z:array[1..10] of integer;
    i:integer;
   
procedure swap(var c1,c2:integer);
 var c:integer;
 begin
   c:=c1;
   c1:=c2;
   c2:=c;
 end;
 
    
procedure QSort(Var A, E: integer);
var l, r, Pivot, ip: integer;
begin
   ip := (A+E) div 2;
   Pivot := z[ip];
   l := A;
   r := E;
   repeat
      while z[l] < Pivot do inc(l);
      while z[r] > Pivot do dec(r);
      if l <= r then begin
                     swap(z[l],z[r]);
                     inc(l);
                     dec(r);
                  end;
      l := l+1;
      r := r-1;
   until (r < l);
   
   if A < r then QSort(A,r);
   if l < E then QSort(l,E);
end;
 
 
 
BEGIN
   for i := 1 to 10 do begin
                      write('z(',i,') = ');
                      read(z);
                  end;
   
   QSort(1,10);
end.     

Windsurfer

  • Sr. Member
  • ****
  • Posts: 362
    • Windsurfer
Re: QuickSort
« Reply #1 on: February 28, 2016, 11:54:23 am »
RosettaCode is a good site for examples:

Code: Pascal  [Select]
  1. http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Pascal

GetMem

  • Hero Member
  • *****
  • Posts: 3419
Re: QuickSort
« Reply #2 on: February 28, 2016, 12:10:40 pm »
Try this:
Code: Pascal  [Select]
  1. program Quicksort;
  2.  
  3. procedure QuickSort(var AI: array of Integer; ALo, AHi: Integer);
  4. var
  5.   Lo, Hi, Pivot, T: Integer;
  6. begin
  7.   Lo := ALo;
  8.   Hi := AHi;
  9.   Pivot := AI[(Lo + Hi) div 2];
  10.   repeat
  11.     while AI[Lo] < Pivot do
  12.       Inc(Lo) ;
  13.     while AI[Hi] > Pivot do
  14.       Dec(Hi) ;
  15.     if Lo <= Hi then
  16.     begin
  17.       T := AI[Lo];
  18.       AI[Lo] := AI[Hi];
  19.       AI[Hi] := T;
  20.       Inc(Lo) ;
  21.       Dec(Hi) ;
  22.     end;
  23.   until Lo > Hi;
  24.   if Hi > ALo then
  25.     QuickSort(AI, ALo, Hi) ;
  26.   if Lo < AHi then
  27.     QuickSort(AI, Lo, AHi) ;
  28. end;
  29.  
  30.  
  31. var
  32.   AI: array of Integer;
  33.   I: Integer;
  34.   Len: Integer;
  35. begin
  36.   Write('Array length: ');
  37.   Readln(Len);
  38.   SetLength(AI, Len);
  39.   for I := Low(AI) to High(AI) do
  40.   begin
  41.     Write('AI(',I + 1,') = ');
  42.     Readln(AI[I]);
  43.   end;
  44.  
  45.   QuickSort(AI, Low(AI), High(AI));
  46.  
  47.   for I := Low(AI) to High(AI) do
  48.     Writeln('AI(',I + 1,') = ', AI[I]);
  49.   Readln;
  50. end.
« Last Edit: February 28, 2016, 12:14:05 pm by GetMem »