|
1 | 1 | # SORT |
2 | 2 |
|
3 | | -> SORT array [USE cmpfunc] |
| 3 | +> SORT byref A [USE cmpfunc( x, y )] |
4 | 4 |
|
5 | | -Sorts an array. The cmpfunc if specified, takes 2 vars to compare and must return: -1 if x < y, +1 if x > y, 0 if x = y. |
| 5 | +Sorts an array `A` in ascending order. The sorted array is return as `A`, therefore overwriting the initial array. If a compare function `cmpfunc` is specified, |
| 6 | +this function will be used for comparision. The compare function takes two elements of `A` as `x`, `y` to compare and must return: |
6 | 7 |
|
| 8 | +- `-1` if `x` is to be placed before `y` |
| 9 | +- `1` if `y` is to be placed before `x` |
| 10 | +- `0` if it doesn't matter which is placed first (which is usually the case when the elements are equal) |
| 11 | + |
| 12 | +### Example 1: Sorting in ascending order |
| 13 | + |
| 14 | +``` |
| 15 | +A = [5, 3, 8, 2, 1, 7, 9] |
| 16 | +sort A |
| 17 | +print A ' Output [1,2,3,5,7,8,9] |
7 | 18 | ``` |
8 | | -FUNC qscmp(x,y) |
9 | | -IF x=y |
10 | | - qscmp=0 |
11 | | -ELIF x>y |
12 | | - qscmp=1 |
13 | | -ELSE |
14 | | - qscmp=-1 |
15 | | -ENDIF |
16 | | -END |
17 | | -... |
18 | | -DIM A(5) |
19 | | -FOR i=0 TO 5 |
20 | | - A(i)=RND |
21 | | -NEXT |
22 | | -SORT A USE qscmp(x,y) |
| 19 | + |
| 20 | +### Example 2: Sorting in ascending order using a compare function |
| 21 | + |
23 | 22 | ``` |
| 23 | +func cmpfunc_ascending(x, y) |
| 24 | + if x == y |
| 25 | + return 0 |
| 26 | + elseif x > y |
| 27 | + return 1 |
| 28 | + else |
| 29 | + return -1 |
| 30 | + endif |
| 31 | +end |
24 | 32 |
|
| 33 | +A = [5, 3, 8, 2, 1, 7, 9] |
| 34 | +sort A use cmpfunc_ascending(x, y) |
| 35 | +print A ' Output [1,2,3,5,7,8,9] |
| 36 | +``` |
| 37 | + |
| 38 | +### Example 3: Sorting in descending order using a compare function |
| 39 | + |
| 40 | +``` |
| 41 | +func cmpfunc_descending(x, y) |
| 42 | + if x == y |
| 43 | + return 0 |
| 44 | + elseif x < y |
| 45 | + return 1 |
| 46 | + else |
| 47 | + return -1 |
| 48 | + endif |
| 49 | +end |
| 50 | +
|
| 51 | +A = [5, 3, 8, 2, 1, 7, 9] |
| 52 | +sort A use cmpfunc_descending(x, y) |
| 53 | +print A ' Output [9,8,7,5,3,2,1] |
| 54 | +``` |
0 commit comments