Built-in sorting methods
Python has a built-in quick sort function called
sorted() and
sort(). It uses the
Timsort.
Consider using the built-in sort functions.
1) Getting a new array
B that matches the array
A sorted in ascending order (by default, sorting in ascending order):
B = sorted(A)
2) Getting a new array B that matches the array A sorted in descending order:
B = sorted(A, reverse = True)
reverse - translated from English "reverse".
3) To perform non-standard sorting, a sorting key is required - the argument key.
To sort in ascending order by the last digit of a number, the key will be the last digit of the number.
To do this, you need to write a function that will return the required key to us - in our case, the last digit of the number.
# a function that returns the sort key
# - the last digit of the number
def lastDigit(n):
return n%10
B = sorted(A, key = lastDigit)
4) Using the lambda function - function without a name.
If you do not want to write a separate function, because of its simplicity, then you can use the so-called lambda functions. Such functions are written directly when called in the key parameter.
B = sorted(A, key = lambda x: x % 10)
5) If you need to sort the array "in place" (without allocating an extra array), it's better to use the sort().
method
For example, sorting the array A by the last digit in descending order looks like this:
A.sort(key = lambda x: x % 10, reverse = True)