Comparing sorting types in Pascal - pascal

I am going to write a program that asks the user to enter items then choose the sorting type to sort them (bubble, inserion and selection).
After that I have to compare these types by time efficiency.
I wrote code for the first part, but I didn't know how to use a function in Pascal to write the second part (comparison).
This is what I have done:
Begin
writeln('How many Number you would like to sort:');
readln(size);
For m := 1 to size do
Begin
if m=1 then
begin
writeln('');
writeln('Input the first value: ');
readln(IntArray[m]);
end
else if m=size then
begin
writeln('Input the last value: ');
readln(IntArray[m]);
end
else
begin
writeln('Input the next value: ');
readln(IntArray[m]);
End;
End;
writeln('Values Before The Sort: ');
for m:=0 to size-1 do
writeln(IntArray[m+1]);
writeln();
begin
repeat
writeln(' ~*~...~*~ ~*~...~*~ ~*~...~*~ ~*~...~*~');
writeln('1. Insertion Sort.');
writeln('2. Bubble Sort.');
writeln('3. Selection Sort. ');
writeln('4. Exist ');
writeln('');
writeln('Enter your choice number: ');
readln(sort);
case sort of
1: begin {when choice = 1}
writeln('');
writeln(' The sorted numbers by Insertion sort are ~> ');
For i := 2 to size do
Begin
index := intarray[i];
j := i;
While ((j > 1) AND (intarray[j-1] > index)) do
Begin
intarray[j] := intarray[j-1];
j := j - 1;
End;
intarray[j] := index;
End;
for i:= 1 to size do
writeln(intarray[i]);
end;
2: begin {when choice = 2}
writeln('');
writeln(' The sorted numbers by bubble sort are ~> ');
For i := size-1 DownTo 1 do
For j := 2 to i do
If (intArray[j-1] > intarray[j]) then
Begin
temp := intarray[j-1];
intarray[j-1] := intarray[j];
intarray[j] := temp;
End;
for i:= 1 to size do
writeln(intarray[i]);
end;
3: begin {when choice = 3}
writeln('');
writeln(' The sorted numbers by selection sort are ~> ');
for i:=1 to size do
begin
j:= i ;
for index:= i +1 to size do
if intarray[index]<intarray[j] then
j:=index;
temp:=intarray[j];
intarray[j]:=intarray[i];
intarray[i]:=temp;
end;
for i:= 1 to size do
writeln(intarray[i]);
end;
4: begin
writeln('*~...~*~ Thank U For used Our Program We Hope You Enjoyed ~*~...~*~ ');
end;
end;
until sort = 4 ;
end;
end.
I hope that I will find the answer here...

I hope you know the TIME complexity of Bubble, Insertion and Selection sort.
If you know you can just compare like that
if (time_complexity_bub>time_complexity_ins)and(time_complexity_bub>time_complexity_sel) then writeln('Bubble Sort is the WORST !!!');
if (time_complexity_ins>time_complexity_bub)and(time_complexity_ins>time_complexity_sel) then writeln('Insertion Sort is the WORST !!!');
if (time_complexity_sel>time_complexity_ins)and(time_complexity_bub<time_complexity_sel) then writeln('Selection Sort is the WORST !!!');
If you have other questions you can ask me :D ...

Pascal supports >,>=,=,<= and < for comparison, but it seems you already know this:
if intarray[index]<intarray[j] then
So maybe you have to explain your question a bit clearer.

I think author is not sure how to measure time in Pascal.
I don't know what compiler you're using, but overall pattern is like:
var
startTime : TDateTime;
overallTime : TDateTime;
begin
startTime := SomeFunctionToGetCurrentTimeWithMicroseconds;
SomeLongOperation;
overalltime := SomeFunctionToGetCurrentTimeWithMicroseconds() - startTime;
end.

Related

Not understanding array merging procedure in merge sort procedure

I've been trying to learn the procedure for merging two arrays in merge sort, and I've been given a fixed code which I have to strictly follow .The following is a program for sorting a list of numbers in ascending/ descending order depending on the user's choice is as follows:
const
max = 200000;
MaxDisp = 20;
type
list = array[1..max] of real;
var
a: list;
na: longint;
is_asc:boolean;
procedure GenList(var L: list; n: longint);
var
i: longint;
begin
randomize;
for i := 1 to n do begin
L[i] := random;
end;
end;
procedure DispList(L: list; n: longint);
var
i: longint;
begin
for i := 1 to MaxDisp do begin
if i <= n then begin
writeln(i:10, ' - ', L[i]:0:10);
end;
end;
if n > MaxDisp then begin
writeln(n - MaxDisp, ' more ...');
end;
end;
procedure sort(var L: list; n: longint;is_asc:boolean);
procedure Merge(L1,L2,R1,R2:longint);
var
M:list;//this is C
i1,i2,iM,i,j:longint;
begin
i1:=L1;
i2:=L2;
j:=1;
while (i1<=R1) and (i2<=R2) do begin
if (is_asc and (L[i1]<L[i2])) or not is_asc and (L[i1]<L[i2]) then begin
M[j]:=L[i1];
j:=j+1;
i1:=i1+1;
end
else begin
M[j]:=L[i2];
j:=j+1;
i2:=i2+1;
end;
j:=________;
end;
if(i1>R1) and (i2<=R2) then
for i:=________ do begin
M[j]:=_______;
end
else if (i2>R2) and (i1<=R1) then
for i:=1 to _______ do begin
_________;
end;
num:=_______;
i:=______;
for j:=1 to num do begin
_________;
end
end;
procedure MSort(LL,RR:longint);
var mid:integer;
begin
if LL<RR then begin
mid:=(LL+RR) div 2;
MSort(LL,mid);
MSort(mid+1,RR);
Merge(LL,mid,mid+1,RR);
end
end;
begin
MSort(1,n);
end;
function is_sorted(L: list; n:longint;is_asc:boolean): boolean;
var
i: longint;
flag: boolean;
begin
flag := true;
i := 1;
while flag and (i < n) do begin
flag := ((L[i]<=L[i+1]) and (is_asc)) or (not(is_asc) and (L[i]>=L[i+1]));
i := i + 1;
end;
is_sorted := flag;
end;
begin
na := MaxDisp;
GenList(a, na);
writeln(na, ' random items:');
DispList(a, na);
writeln('Press <Enter> to sort the list in ascending order ...');
readln;
sort(a, na,is_asc);
DispList(a, na);
writeln('Sorted in ascending order: ', is_sorted(a, na,is_asc));
write('Press <Enter> to continue ...');
readln;
end.
Except for the blank parts, I understand what the other parts of the code are doing, including the first part of the procedure Merge, which I think is just merging the arrays in L into M, and I think the following part is writing about the cases in case i1 and i2 are larger than L1 and L2, but I don't understand what the problem if this happens or what should be done. After this the following parts of the procedure Merge I have no idea what it is supposed to be doing.
I don't know this language (indexes start at 1?), but this is what I think needs changing:
i1:=L1;
i2:=L2;
j:=1;
while (i1<=R1) and (i2<=R2) do begin
if (is_asc and (L[i1]<L[i2])) or not is_asc and (L[i1]<L[i2]) then begin
M[j]:=L[i1];
j:=j+1;
i1:=i1+1;
end
else begin
M[j]:=L[i2];
j:=j+1;
i2:=i2+1;
end;
// j:=________; // don't change j
end;
while(i1 <= R1) do begin // copy rest of run 1 if any elements
M[j]:=L[i1];
j:=j+1;
i1:=i1+1;
end
while(i2 <= R2) do begin // copy rest of run 2 if any elements
M[j]:=L[i2];
j:=j+1;
i2:=i2+1;
end
for(i = 1 to j) do begin // copy M back into L
L[i+L1-1] := M[j]; // I'm not sure about the -1
end
end;

Pascal bubble sort print each sorted line

I have my bubble sorting algorithm which works correctly but I want to set it up so it prints each line in the process of the final output(19 lines).I have tried almost everything, but it doesn't print correctly:
program Bubble_Sort;
const N = 20;
var
d : array[1..N] of integer;
var
i,j,x : integer;
begin
randomize;
for i := 1 to N do d[i] := random(100);
writeln('Before sorting:'); writeln;
for i := 1 to N do write(d[i], ' ');
writeln;
for j := 1 to N - 1 do
for i := 1 to N - 1 do
write(d[i], ' ');
if d[i] > d[i+1] then
begin
x := d[i]; d[i] := d[i+1]; d[i+1] := x;
end;
writeln('After sorting:'); writeln;
for i := 1 to N do write(d[i], ' ');
writeln;
end.
The outer loop in the center of your code, the for j ... loop runs for each bubble iteration. That is where you want to output the state of the sorting. Because you thus have more than one statement within that for j ... loop, you must also add a begin .. end pair:
for j := 1 to N - 1 do
begin
//one round of sorting
//display result so far
end;
The sorting is ok as you have it, except when you added the write(d[i], ' '); presumably to output the sort result for one iteration, you changed the execution order to become totally wrong.
Remove the write(d[i], ' '); from where it is now.
To display the sorting result after each iteration add a new for k ... loop and a writeln;
for k := 1 to N do
write(d[k], ' ');
writeln;
Final sorting and progress display should be structured like:
for j := 1 to N - 1 do
begin
for i := 1 to N - 1 do
// one round of sorting
for k := 1 to N - 1 do
// output result of one sorting round
end;

Insertion Sort - TStringList Delphi

i'm trying to sort TStringList of integers from a text file with Insertion and Selection Sort .Selection Sort works ok , but the Insertion Sort doesnt work with my code . Can someone tell me where i'm wrong ? My 'numbers.txt' has 5000 lines of numbers. Thanks in advance
UPDATE : I have edited my code a bit , it works now with Insertion-Sort but it sorts just 4 indexes of integer as on the image
var
i, Position, n: integer;
Value: string;
begin
n := Items.Count;
for i := 1 to n - 1 do
begin
Value := Items[i];
Position := i-1;
while (Position >0) and (Items[Position]>Value) do
begin
Items[Position+1]:= Items[Position] ;
Position := Position -1 ;
end;
Items[Position+1] := Value;
end;
end;
Your data in the image is sorting exactly as it should, because you're sorting on string values, and based on the comparison you're making the order is perfect. "1143" falls exactly between the string values "11413" and "11443", because the comparison is made character by character out to the length of the shortest of the values. "1141" < "1143" < "1144", based on the first four characters of each string.
If you want an actual integer sort, then you need to convert the two values to integer before comparing them. Something like this should work (note I did not test your overall sort logic - I just used values that demonstrate the concept):
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.Classes;
var
i, Position, n: integer;
Value: integer;
Items: TStringList;
begin
Items := TStringList.Create;
try
Items.DelimitedText := '1116,11170,11178,11206,1122,11221,11228';
n := Items.Count;
for i := 1 to n - 1 do
begin
Value := StrToInt(Items[i]);
Position := i - 1;
while (Position > 0) and (StrToInt(Items[Position]) > Value) do
begin
Items[Position + 1]:= Items[Position];
Position := Position - 1 ;
end;
Items[Position+1] := IntToStr(Value);
end;
for i := 0 to Items.Count - 1 do
WriteLn(Items[i]);
finally
Items.Free;
end;
ReadLn;
end.
The output I got from the code above in a console window:
1116
1122
11170
11178
11206
11221
11228

Pascal error: left side cannot be assigned when trying to compile

I got this error when trying to compile.
left side cannot be assign to, ./number 21,22 in pastebin
here is my code
Program urut;
Uses Wincrt;
Const N = 5;
data: Array [1..N] Of Integer = (2,4,5,3,1);
Var
j,k,temp : Integer;
Begin
Clrscr;
Writeln ('Data sebelum diurutkan');
For j:=1 To N Do
Begin
Writeln('data[' ,j, ']= ',data [j]);
End;
For j:=1 To N-1 Do
Begin
For k :=N Downto j+1 Do
Begin
If data[k] < data[k-1] Then
Begin
temp := data[k];
data[k] := data[k-1]; //left side cannot be assigned to
data[k-1] := temp; //left side cannot be assigned to
End;
End;
End;
Writeln;
Writeln ('Data setelah diurutkan ');
For j:=1 To N Do
Begin
Writeln ('data[' ,j, '] = ',data[j]);
End;
Writeln;
End.
sorry for uncorrectly pattern post
, thank you so much.
Like tom Tom Brunberg says, my array is const, it can't be changed. Therefore I need to remove that const.
So it should be
data: Array [1..5] Of Integer = (value);
without const, and put it under var with another variable

All sums of a number

I need an algorithm to print all possible sums of a number (partitions).
For example: for 5 I want to print:
1+1+1+1+1
1+1+1+2
1+1+3
1+2+2
1+4
2+3
5
I am writing my code in Pascal. So far I have this:
Program Partition;
Var
pole :Array [0..100] of integer;
n :integer;
{functions and procedures}
function Minimum(a, b :integer): integer;
Begin
if (a > b) then Minimum := b
else Minimum := a;
End;
procedure Rozloz(cislo, i :integer);
Var
j, soucet :integer;
Begin
soucet := 0;
if (cislo = 0) then
begin
for j := i - 1 downto 1 do
begin
soucet := soucet + pole[j];
if (soucet <> n) then
Write(pole[j], '+')
else Write(pole[j]);
end;
soucet := 0;
Writeln()
end
else
begin
for j := 1 to Minimum(cislo, pole[i - 1]) do
begin
pole[i] := j;
Rozloz(cislo - j, i + 1);
end;
end;
End;
{functions and procedures}
{Main program}
Begin
Read(n);
pole[0] := 101;
Rozloz(n, 1);
Readln;
End.
It works good but instead of output I want I get this:
1+1+1+1+1
2+1+1+1
2+2+1
3+1+1
3+2
4+1
5
I can't figure out how to print it in right way. Thank you for help
EDIT: changing for j:=i-1 downto 1 to for j:=1 to i-1 solves one problem. But my output is still this: (1+1+1+1+1) (2+1+1+1) (2+2+1) (3+1+1) (3+2) (4+1) (5) but it should be: (1+1+1+1+1) (1+1+1+2) (1+1+3) (1+2+2) (1+4) (2+3) (5) Main problem is with the 5th and the 6th element. They should be in the opposite order.
I won't attempt Pascal, but here is pseudocode for a solution that prints things in the order that you want.
procedure print_partition(partition);
print "("
print partition.join("+")
print ") "
procedure finish_and_print_all_partitions(partition, i, n):
for j in (i..(n/2)):
partition.append(j)
finish_and_print_all_partitions(partition, j, n-j)
partition.pop()
partition.append(n)
print_partition(partition)
partition.pop()
procedure print_all_partitions(n):
finish_and_print_all_partitions([], 1, n)

Resources