Direct arranging of an array

FlamingClaw

This example is demonstrates a solution for direct arranging
By FlamingClaw

221 Views
About the Author

Just living in hungary.Teaching myself in pascal.
I have time to programming when I'm going to home,cause my job is not a good place for that.
Don't forget that if you ask something on the forum and you got the right answer then
[b] mark as solved !![/b]

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);
     ReadLn;
     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);
     ReadKey;
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=-
}
Morten Brendefu 28 Light Poster

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 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.