qsort.pp 1.9 KB

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