Im new to loops on mathematica,was wondering how could I create a function to loop through a list which finds the index of the smallest value of that list, makes a sublist from index 1 to that smallest value and one for the rest of the list, reverse first sub list then join it to the sublist with the rest of the list. To keep going till the list is ordered in increasing order. Thank you
1 Answer
First, loops are seldom needed in MMA, there are more efficient operators for this, e.g. "Map".
Second, your algorithm does not order the list. After the first round, the smallest element is at the beginning and nothing changes anymore. To make it work you must, in round i, only take the elemnts i+1,.. to feed into your algorithm.
Here is your algorithm with correction, however note, this is a pretty inefficient way to sort a list:
sort0[list_] := Module[{pos},
pos = Position[list, Min[list]][[1, 1]];
Join[Reverse[list[[;; pos]]], list[[pos + 1 ;;]]]
];
sort[list0_] := Module[{list = list0, i = 0},
While[ ! OrderedQ[list],
list = Join[list[[;; i]], sort0[list[[++i ;;]]]];
];
list
]
To test it:
list = RandomReal[1, 6]
sort[list]
{3, 2, 5, 1, 4}
. The index of the smallest value is4
, the sublist is{3, 2, 5, 1}
, reverse and join with the rest of the list{1, 5, 2, 3, 4}
. Now the index of the smallest value is1
so applying the procedure results in the same list. $\endgroup$