2016-11-25 104 views
-3
procedure arranging; 
var 
    i,j,h : integer; 
    c : real; 
begin 
    for i := 1 to n - 1 do 
    begin 
    h := i; 
    for j := i + 1 to n do 
     If D[j] > D[h] then 
     j := h; 
    c := D[i]; 
    D[i] := D[h]; 
    D[h] := c; 
    end; 
end; 

這是如何從我的PASCAL編程的書環,並且這個過程應安排從最大的一個數組到最小,該陣列是爲.txt文件,還有已經在另一個過程讀取它(N是數組的長度)。我不明白這是如何循環工作:(你能解釋一下嗎?(第一次詢問在這裏,請不要判斷)帕斯卡,給我解釋一下這個循環工作

+1

歡迎來到Stack Overflow!請參考[遊覽](http://stackoverflow.com/tour),環顧四周,並閱讀[幫助中心](http://stackoverflow.com/help),特別是_ [我如何問一個好問題?](http://stackoverflow.com/help/how-to-ask)_。 – Cagy79

+1

_explain me_是對SO開始提問的錯誤措辭。請查看幫助中心,走[這趟(http://stackoverflow.com/tour),看看有什麼要問及如何。 –

+0

還有其他更有效的排序算法,如快速排序。通過google搜索查看youtube上各種排序算法的跳舞解釋:https://www.google.com/#q=SORT+ARRAY+DANCE+youtube –

回答

1

中有你的算法錯誤。
j := h;行應該做相反的h是數組中最高值的索引,從i開始計數,所以當內循環完成時,索引h指向最大值,之後將看到pos ih,使得D [i]具有最大值。

下一個內循環從前一個位置開始1個位置,並且重複直到下一個最大值va在數組中找到並放入正確的位置。等等。

procedure arranging; 
var 
    i,j,h : integer; 
    c : real; 
begin 
    for i := 1 to n - 1 do // Loop all values but the last 
    begin 
    h := i; // <-- Assume largest value in index i 
    for j := i + 1 to n do // Loop from i+1 to last value 
     If D[j] > D[h] then 
     h := j; // <-- h points to largest array value so far 
    c := D[i]; // Save D[i] to a temporary storage 
    D[i] := D[h]; // Now swap values so D[i] has the largest value 
    D[h] := c; 
    end; 
end;