0
$\begingroup$

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

$\endgroup$
2
  • 1
    $\begingroup$ This procedure will not sort the list. Consider {3, 2, 5, 1, 4}. The index of the smallest value is 4, 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 is 1 so applying the procedure results in the same list. $\endgroup$ Commented Nov 27, 2022 at 21:12
  • 1
    $\begingroup$ Similar question here. $\endgroup$ Commented Nov 27, 2022 at 21:13

1 Answer 1

1
$\begingroup$

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]

enter image description here

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.