# how to sort a list without build-in function

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.

• Why aren't you using Sort? Is this homework? Also you should use a semicolon ; instead of a comma , before calling sort. – ktm Dec 29 '18 at 19:41
• There are more than a dozen methods of sorting (BubbleSort, QuickSort, MergeSort, HeapSort, InsertionSort, IntroSort, SelectionSort, ...). – David G. Stork Dec 29 '18 at 19:43
• 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 :) – raihan hossain Dec 29 '18 at 19:54
• Look up 'HoldFirst'. – Daniel Lichtblau Dec 29 '18 at 21:14

## 1 Answer

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 ;-)

• Yes.finally got it.Thanks @mgamer Sir for your advice. – raihan hossain Dec 30 '18 at 11:37
• @mgamer Very tricky!!! I tried to test it bubbleRule[{1, 5, 2, 4, 3}] but MMA doesn't sort... – Ulrich Neumann Dec 30 '18 at 14:13
• @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 – mgamer Dec 31 '18 at 10:40
• @mgamer Thanks! – Ulrich Neumann Dec 31 '18 at 13:10