2016-11-27 42 views
-2

我该如何去执行使用selection sort作为整数数组,按升序排序?我相信这个语法会包含一个for循环,但我不确定这个语法是如何工作的。使用Ada的选择排序

for I in 1..20 loop 
    TempLowest : Integer := 99999; 
    if Value(I) < TempLowest then 
     Value(I) := TempLowest; 
    end if; 
end loop; 

我想它是这样的东西,但我不太明白这将如何组织我的数组从降序到​​升序。谢谢您的帮助。

+0

我觉得它可能会帮助,如果你描述ŧ他用Ada的近似*算法,并且不太在意语法。现在,您正尝试创建一个20'99999'的数组(技术上已分类)。 –

+0

想象一下,值(1)是一些数字12000例如和价值(2)是15000例如,等等......这就是我想要排序,价值(我),我是1-20其中值的每次迭代(I)是一个不同的值。 – Dibs

+0

您的问题已经通过链接到维基百科文章的选择排序进行编辑。这应该有所帮助。 –

回答

0

Selection_Sort.ads

package Selection_Sort is 

    type Array_T is array (Natural range <>) of Integer; -- Array type 
    procedure Sort (Array_To_Sort : in out Array_T); -- Sort the array 
    procedure Print (Array_To_Print : in Array_T); -- Output the array 

end Selection_Sort; 

Selection_Sort.adb

with Ada.Text_IO; 

package body Selection_Sort is 

    procedure Sort (Array_To_Sort : in out Array_T) is 
    begin 
     for i in Array_To_Sort'Range 
     loop 
     declare 
      minimum_index : Natural := i; 
     begin 
      for j in i+1 .. Array_To_Sort'Last 
      loop 
       if Array_To_Sort(j) < Array_To_Sort(minimum_index) then 
        minimum_index := j; 
       end if; 
      end loop; 
      if minimum_index /= i then 
       -- Swap 
       declare 
        temp : Integer := Array_To_Sort(minimum_index); 
       begin 
        Array_To_Sort(minimum_index) := Array_To_Sort(i); 
        Array_To_Sort(i) := temp; 
       end; 
      end if; 
     end; 
     end loop; 
    end Sort; 

    procedure Print (Array_To_Print : in Array_T) is 
    begin 
     Ada.Text_IO.Put ("Array_To_Print: ("); 
     for i in Array_To_Print'Range 
     loop 
     Ada.Text_IO.Put(Integer'Image(Array_To_Print(i))); 
     end loop; 
     Ada.Text_IO.Put_Line(")"); 
    end Print; 

begin 
    null; 
end Selection_Sort; 

Main.adb

with Selection_Sort; 
with Ada.Text_IO; 
with Ada.Exceptions; 

procedure Main is 
    --My_Array : Selection_Sort.Array_T := (77,6,7,3,4,11,60,23,34,11); 
    --My_Array : Selection_Sort.Array_T := (1,2,3,4,5,6,7,8,9,10); 
    My_Array : Selection_Sort.Array_T := (10,9,8,7,6,5,4,3,2,1); 
begin 
    Selection_Sort.Print(Array_To_Print => My_Array); 
    Selection_Sort.Sort(Array_To_Sort => My_Array); 
    Selection_Sort.Print(Array_To_Print => My_Array); 
exception 
    when E: others => 
     Ada.Text_IO.Put_Line("Exception: " & 
          Ada.Exceptions.Exception_Information(E)); 
end Main;