Answer the question
In order to leave comments, you need to log in
How to convert the algorithm for finding different elements in an array?
Given an array with elements of type byte. We need to find out the number of
different elements in it. The number of actions must be
of the order of cn, where n is the length of the array.
I made a task in pascalABC, it works great. but there is one BUT. The complexity of the algorithm should be cn, not n^2 (like mine).
This means you need to remove the nesting of the for loop.
I don't know what to do anymore, I can't imagine such an algorithm...
Listing below:
program zadacha;
const
nmax=100;
type
tArr=array[1..nmax] of byte;
var
a,b: tArr;
i,j,n,m,k: byte;
procedure fillArray(var a:tArr);
var i:integer;
start
randomize;
for i:=1 to n do
begin
a[i]:=random(20)-10;
end;
end;
procedure printArray(a:tArr;n:byte);
var i:integer;
begin
for i:=1 to n do
begin
write(a[i],' ');
end;
end;
procedure findUnique(var a,b:tArr);
var i,j:integer;
begin
for i:=1 to n do
begin
k:=0;
for j:=1 to n do
begin
if a[i]=a[j] then
inc(k);
end;
if k=1 then
begin
inc(m);
b[m]:=a[i];
end;
end;
end;
beginm
:=0; k:=0;
write('Enter the size of the array: '); readln(n);
fillArray(a);
writeln('Array:');
printArray(a,n);
writeln;
findUnique(a,b);
writeln('Array of unequal numbers:');
printArray(b,m);
end.
Help me please.
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question