1

さて、私はこのコードに問題があります、それはMathematicaで選択ソートアルゴリズムを書くことについてですが、逆に、つまり、最小の数を検索してリストの最初の位置に配置する代わりに、検索する必要があります最大のものを最後の位置に置きます。私はこのコードを書きましたが、Mathematicaを初めて使用するため、解決策を見つけることができません。リストはソートされません。読んでいただきありがとうございます、あなたの答えは役に立ちます!

      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 <= Length@L, temp = xi[[n]];
   For[j = n, j <= Length@L, j++, If[xi[[j]] < temp, temp = xi[[j]]];];
   xi[[n ;;]] = {temp}~Join~
     Delete[xi[[n ;;]], First@Position[xi[[n ;;]], temp]];
   n++;];
  xi]
Print[L]
4

1 に答える 1

0

ここに作業バージョンがあります。関数では、SelectSort[]関数変数をパターン変数に変更するだけで済みましたL_。それ以外はうまくいくようです。

(* Function definition *)
SelectSort[L_] := Module[{n = 1, temp, xi = L, j},
  While[n <= Length@L,
   temp = xi[[n]];
   For[j = n, j <= Length@L, j++,
    If[xi[[j]] < temp, temp = xi[[j]]];
    ];
   xi[[n ;;]] = {temp}~Join~
     Delete[xi[[n ;;]], First@Position[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.

于 2012-09-13T08:01:02.263 に答える