qsort.pp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1993-2005 by the Free Pascal Development Team
  4. QuickSort Example
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. program quicksort;
  12. const
  13. {$ifndef MACOS}
  14. max = 100000;
  15. {$else}
  16. max = 1000; {Actually it works with 100000 also, but that might }
  17. {lead problems occacionally.}
  18. {$endif}
  19. type
  20. tlist = array[1..max] of longint;
  21. var
  22. data : tlist;
  23. procedure qsort(var a : tlist);
  24. procedure sort(l,r: longint);
  25. var
  26. i,j,x,y: longint;
  27. begin
  28. i:=l;
  29. j:=r;
  30. x:=a[(l+r) div 2];
  31. repeat
  32. while a[i]<x do
  33. inc(i);
  34. while x<a[j] do
  35. dec(j);
  36. if not(i>j) then
  37. begin
  38. y:=a[i];
  39. a[i]:=a[j];
  40. a[j]:=y;
  41. inc(i);
  42. j:=j-1;
  43. end;
  44. until i>j;
  45. if l<j then
  46. sort(l,j);
  47. if i<r then
  48. sort(i,r);
  49. end;
  50. begin
  51. sort(1,max);
  52. end;
  53. var
  54. i : longint;
  55. begin
  56. write('Creating ',Max,' random numbers between 1 and 500000');
  57. randomize;
  58. for i:=1 to max do
  59. data[i]:=random(500000);
  60. writeln;
  61. writeln('Sorting...');
  62. qsort(data);
  63. writeln;
  64. for i:=1 to max do
  65. begin
  66. write(data[i]:7);
  67. if (i mod 10)=0 then
  68. writeln;
  69. end;
  70. end.