2012-09-13 95 views
1

嗯,我有這個代碼的麻煩,它是關於在Mathematica中寫選擇排序算法,但倒過來,我的意思是,而不是搜索最小的數字,並將其放置在列表中的第一個位置,我需要搜索最大的一個,並將其放在最後一個位置。 我已經寫了這段代碼,但是因爲我是Mathematica的新手,我找不到解決方案。它不排序列表。非常感謝您的閱讀,您的答案將是有益的!「倒」選擇排序Mathematica 8

 L = {}; 
n = Input["Input the size of the list (a number): "]; 
For[i = 1, i <= n, m = Input["Input a number to place in the list:"]; 
L = Append[L, m]; i++] 
SelectSort[L] := 
Module[{n = 1, temp, xi = L, j}, While[n <= [email protected], temp = xi[[n]]; 
    For[j = n, j <= [email protected], j++, If[xi[[j]] < temp, temp = xi[[j]]];]; 
    xi[[n ;;]] = {temp}~Join~ 
    Delete[xi[[n ;;]], [email protected][xi[[n ;;]], temp]]; 
    n++;]; 
    xi] 
Print[L] 
+0

何塞:你是第一位,第一位,第二位,第三位,第二位,第三位。 Te recomiendo que leas las常見問題解答Con este comportamiento tus preguntasrecibiráncada vez menosatención。順便說一句:你不應該在Mathematica中使用循環。它被設計成一個功能性的,長期的rewiting系統。 –

+1

Gracias Belisarius,por ser un poco nuevo aqui nosabíamucho sobre lo de aceptar las respuestas peroempezaréa hacerlo,gracias! – dlvx

+0

也檢查這個姊妹網站http://mathematica.stackexchange.com。對Mathematica問題更好 –

回答

0

這是一個工作版本。在SelectSort[]函數中,我只需將函數變量更改爲模式變量,即L_。除此之外,它似乎工作。

(* Function definition *) 
SelectSort[L_] := Module[{n = 1, temp, xi = L, j}, 
    While[n <= [email protected], 
    temp = xi[[n]]; 
    For[j = n, j <= [email protected], j++, 
    If[xi[[j]] < temp, temp = xi[[j]]]; 
    ]; 
    xi[[n ;;]] = {temp}~Join~ 
    Delete[xi[[n ;;]], [email protected][xi[[n ;;]], temp]]; 
    n++;]; 
    xi] 

(* Run section *) 
L = {}; 
n = Input["Input the size of the list (a number): "]; 
For[i = 1, i <= n, m = Input["Input a number to place in the list:"]; 
L = Append[L, m]; i++] 
SelectSort[L] 
Print[L] 

{3,3,5,7,8}

{8,3,5,7,3}

的輸出是首先從SelectSort[L]排序列表,則原始輸入列表,L

+0

非常感謝! – dlvx

+0

因爲這段代碼,我很匆忙,實際上有很多東西我仍然不明白從Mathematica – dlvx