Well, I’m having trouble with this code, it’s about writing the Selection Sort alghorithm in Mathematica, but inverted, I mean, instead of searching for the smallest number and place it in the first position of a list, I need to search for the biggest one and place it in the last position.
I’ve written this code but as I’m new to Mathematica, I can’t find the solution. It doesn’t sort the list. Thank you very much for reading, your answers will be helpfull!
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]
Here is a working version. In the
SelectSort[]function I only had to change the function variable to a pattern variable, i.e.L_. Other than that it seems to work.{3, 3, 5, 7, 8}
{8, 3, 5, 7, 3}
The output is first the sorted list from
SelectSort[L], then the original input list,L.