【问题标题】:"Inverted" Selection Sort in Mathematica 8Mathematica 8 中的“倒置”选择排序
【发布时间】:2012-09-13 16:07:15
【问题描述】:

好吧,我在使用这段代码时遇到了问题,它是关于在 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]

【问题讨论】:

  • José: ya hiciste 7 preguntas, no has aceptado ninguna respuesta y no has votado ni una sola vez。 Te recomiendo que leas las FAQs del sitio。 Con este comportamiento tus preguntas recibrán cada vez menos atención。顺便说一句:你不应该在 Mathematica 中使用循环。它被设计成一个功能性的术语重写系统。
  • Gracias Belisarius, por ser un poco nuevo aqui no sabía mucho sobre lo de aceptar las respuestas pero empezaré a hacerlo, gracias!
  • 也可以查看这个姐妹网站mathematica.stackexchange.com。更适合 Mathematica 问题

标签: sorting wolfram-mathematica selection


【解决方案1】:

这是一个工作版本。在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

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 2013-04-25
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    相关资源
    最近更新 更多