Created
May 22, 2019 02:14
-
-
Save newjam/6c2d1cc1c7c517454c348c187f77d9aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Program Quicksort; | |
{ | |
My first Pascal code. | |
Populates and array numbers of length N with random numbers between 1 and M, sorts it in place using quicksort, then prints each element of the list. | |
The quicksort algorithm is translate from C as found in "The Most Beautiful Code I Never Wrote" by Jon Bentley as found in the book "Beautiful Code" | |
} | |
Uses math; | |
Const | |
M = 1000; | |
N = 20; | |
Var | |
numbers : Array [1..N] of Integer; | |
i : Integer; | |
x: Integer; | |
procedure swap(i, j : integer); | |
var | |
x : integer; | |
begin | |
x := numbers[i]; | |
numbers[i] := numbers[j]; | |
numbers[j] := x; | |
end; | |
function randint(i, j : integer) : integer; | |
begin | |
randint := Random(j - i) + i | |
end; | |
procedure quicksort(l, u : integer); | |
var | |
i, m : integer; | |
begin | |
if l < u then | |
begin | |
swap(l, randint(l, u)); | |
m := l; | |
for i := l + 1 to u do | |
if numbers[i] < numbers[l] then | |
begin | |
m := m + 1; | |
swap(m, i); | |
end; | |
swap(l, m); | |
quicksort(l, m - 1); | |
quicksort(m + 1, u); | |
end; | |
end; | |
begin | |
Randomize; | |
for i := 0 to N do begin | |
numbers[i] := randint(1, M); | |
end; | |
quicksort(1, N); | |
for x in numbers do | |
Writeln(x); | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment