2
$\begingroup$

I want to sort a list like below.Without using the build-in function so I tried this:

    sort[n_] := 
     Module[{n0 = n, i, j}, 
      Do[Do[If[n[[j - 1]] > 
           n[[j]], {n[[j - 1]], n[[j]]} = {n[[j]], n[[j - 1]]}],
         {j, Length[n], i, -1}];
       , {i, 1, Length[n] - 1}]; n]
l = {2, 1, 1, 10, 9, 8, 1};sort[l]

But it seem my code is not correct.Can Anyone help me to figure out this. Any hints or solution will be appreciated.

$\endgroup$
  • $\begingroup$ Why aren't you using Sort? Is this homework? Also you should use a semicolon ; instead of a comma , before calling sort. $\endgroup$ – user6014 Dec 29 '18 at 19:41
  • $\begingroup$ There are more than a dozen methods of sorting (BubbleSort, QuickSort, MergeSort, HeapSort, InsertionSort, IntroSort, SelectionSort, ...). $\endgroup$ – David G. Stork Dec 29 '18 at 19:43
  • $\begingroup$ I really need to do it using for/while/Do.it's a problems which was given a contest.So i am excited to solve @user6014 Sir :) $\endgroup$ – raihan hossain Dec 29 '18 at 19:54
  • $\begingroup$ Look up 'HoldFirst'. $\endgroup$ – Daniel Lichtblau Dec 29 '18 at 21:14
2
$\begingroup$

Your code is - nearly - ok. But you return ninstead of n0 and you should work on a temporary variable (n0or here temp). It is always a good idea to use variable names that are (a bit) self explanatory. So make something like:

  sort[list_] := 
     Module[{temp = list, i, j}, 
      Do[Do[If[temp[[j - 1]] > 
           temp[[j]], {temp[[j - 1]], temp[[j]]} = {temp[[j]], temp[[j - 1]]}],
         {j, Length[temp], i, -1}];
       , {i, 1, Length[temp] - 1}]; temp]

I have changed only variable names, for me more easy to read. But.... Bubblesort is one of the worst you can take.

Edit I forgot to mention, that you can implement Bubblesort in a rule-based approach in a oneliner (it is O(n^3), but nice)

bubbleRule[xs___, x_, y_, ys___] := bubbleRule[xs, y, x, ys] /; x > y

Then bubbleRule @ list sorts list ;-)

$\endgroup$
  • $\begingroup$ Yes.finally got it.Thanks @mgamer Sir for your advice. $\endgroup$ – raihan hossain Dec 30 '18 at 11:37
  • $\begingroup$ @mgamer Very tricky!!! I tried to test it bubbleRule[{1, 5, 2, 4, 3}] but MMA doesn't sort... $\endgroup$ – Ulrich Neumann Dec 30 '18 at 14:13
  • $\begingroup$ @UlrichNeumann: By definition bubbleRule has not a list as argument, so you should use ist like: bubbleRule @@ list but you can define: bubbleRule[{xs___, x_, y_, ys___}] := bubbleRule[{xs, y, x, ys}] /; x > y $\endgroup$ – mgamer Dec 31 '18 at 10:40
  • $\begingroup$ @mgamer Thanks! $\endgroup$ – Ulrich Neumann Dec 31 '18 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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