# Direct arranging of an array

This example is demonstrates a solution for direct arranging
By FlamingClaw

``````Program Program01;
Uses Crt;
Const a:Array[0..9]Of Byte =(12,34,7,9,1,67,25,50,2,4);
Var i,j,k:Byte;
{Main}
Begin
ClrScr;
{show the elements of a}
WriteLn('First Run:');
For i:=0 To 9 Do WriteLn(i,'. element: ',a[i]:2);
WriteLn('After Arranging:');
{arranging}
For i:=0 To 8 Do
Begin
For j:=i+1 To 9 Do
Begin
If (a[j] < a[i]) Then
Begin
k:=a[j];
a[j]:=a[i];
a[i]:=k;
End;
End;
End;
{write the results}
For i:=0 To 9 Do WriteLn(i,'. element: ',a[i]:2);
End.

{
-= Note By FlamingClaw =-

-=Direct Arranging=-
The Rules:

Ar:Array[min..max]of element type
i,j,k:element type

Loop1 from i:=min To max-1
Loop2 from j:=i+1 To max   <--this begins from the second element
(*compare two numbers*)
if (Ar[j]<Ar[i]) then  (*if smaller then exchange them*)
k:=Ar[j]             (*save that value to k*)
Ar[j]:=Ar[i]         (*Ar[j].element will A[i].element *)
Ar[i]:=k             (*load the saved value to A[i].element*)
end loop2
end loop1

-= Created By FlamingClaw =-
-=2009.03.22=-
}``````

It works, but Binary sort approach is just sooooo much faster.
This code is good enough though.
It is easy to understand and easy to implement.
Not so with a Binary sort approach or even the more complicated but ultimate speedy approach of Red/Black tree.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.