Can we sort elements in descending order in mojo?

I couldn’t find any working parameters as lambda x: -x or reverse=True in sort() function. Are there any possible solution?
Already, I prefer the following method:

fn main() raises:
    var numbers: List[Int]= [11, 3, 19, 1, 15, 4, 7]
    sort(numbers)
    print("Sorted in ascending order: ", numbers)   
    print("Sorted in descending order: ", numbers[::-1]) 

Please be aware that numbers[::-1] copies the list. See List slicing inconsistency

Then what should I do?

Maybe you can add a cmp_fn parameter that does a descending comparison.
sort[cmp_fn=…](numbers).

1 Like

Maybe it is better to leave the sorted list as is, and print the elements in reverse:

fn main() raises:
    var numbers: List[Int]= [11, 3, 19, 1, 15, 4, 7]
    sort(numbers)
    print("Sorted in ascending order: ", numbers)   
    # print("Sorted in descending order: ", numbers[::-1]) 	# Caution! It copies the list.
    print("Sorted in descending order: [", end = "")
    for i in range(len(numbers)):
        print(numbers[len(numbers)-i -1], end = ", ")
    print("]")
    ```

At last, I found the solution as christoph_schlumpf mentioned:

fn main() raises:
    fn cmp_fn(a: Int, b: Int) capturing -> Bool:
        return a > b

    var numbers: List[Int]= [11, 3, 19, 1, 15, 4, 7]

    sort[cmp_fn](numbers)
  
    print("Sorted in descending order: ", numbers)
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.