Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Functions in Mathematica - sort function

  1. Jan 14, 2010 #1
    Hi ,

    I'm trying to write down the following function :

    sort[list_]

    it needs to sort a list of numbers by checking each two adjacent numbers and swap them
    if it is needed , but it doesn't work . I need to implement it using Pattern Matching .

    but I don't understand how can I interate in "list" , meaning how can I ask an "IF" question
    such as If list < list[i+1] then swap(list,list[i+1]) .

    10x
     
  2. jcsd
  3. Jan 15, 2010 #2

    CompuChip

    User Avatar
    Science Advisor
    Homework Helper

    You are looking for a For loop + If statement?

    Code (Text):

    For[i = 1; i <= Length[list]; i++;
      If[ test; whatToDoIfTestIsTrue; whatToDoIfTestIsFalse]
     
    The last argument (whatToDoIfTestIsFalse) is optional, you can leave it (and the trailing semicolon) out
     
  4. Jan 15, 2010 #3
    Thank you .
    This would do ?

    PHP:
    sort[list_] :=
     For[i = 1 ; i < Length[list]; i++;
      If [ list[i] < list[i + 1] ; j = list[i + 1] ,
       list[i + 1] = list[i], list[i] = j; ]
    ?
     
  5. Jan 17, 2010 #4

    Dale

    Staff: Mentor

    I think you have the semicolons and commas reversed inside the If statement.
     
  6. Jan 18, 2010 #5

    CompuChip

    User Avatar
    Science Advisor
    Homework Helper

    Whoops, you do.

    My bad!
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook