Instagram
youtube
Facebook
Twitter

Sort a NumPy Array in Descending Order

A Sort a NumPy Array in Descending Order?
Code Explanation:
Library Import:
numpy is imported as np to access NumPy functions.
Array Creation: A 1D NumPy array arr is created with unordered numbers.
Sorting in Ascending Order: np.sort(arr) first sorts the array in ascending order: [1 2 3 4].
Reverse the Array: [::-1] is used to reverse the sorted array, converting it to descending order.
Store Result: The reversed sorted array is stored in sorted_arr.
Display Output: print(sorted_arr) prints the final descending array: [4 3 2 1].

 

Program:

import numpy as np

arr = np.array([3, 1, 4, 2])

sorted_arr = np.sort(arr)[::-1]

print(sorted_arr)