Mathematica Functions in Mathematica - sort function

AI Thread Summary
The discussion revolves around implementing a sorting function called "sort" that sorts a list of numbers by comparing adjacent elements and swapping them if necessary, using Pattern Matching. The user seeks guidance on how to iterate through the list and implement an "IF" condition to facilitate the swapping process. Suggestions include using a For loop combined with an If statement to achieve this. The proposed code structure is discussed, with corrections made regarding the placement of semicolons and commas within the If statement. The conversation highlights the importance of proper syntax in programming to ensure the function operates as intended.
Physics_rocks
Messages
12
Reaction score
0
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
 
Physics news on Phys.org
You are looking for a For loop + If statement?

Code:
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
 
CompuChip said:
You are looking for a For loop + If statement?

Code:
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

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

?
 
I think you have the semicolons and commas reversed inside the If statement.
 
Whoops, you do.

My bad!
 

Similar threads

Replies
4
Views
2K
Replies
1
Views
2K
Replies
5
Views
2K
Replies
1
Views
3K
Replies
13
Views
2K
Replies
0
Views
2K
Back
Top