Image

Programs - Python - Arrays

Program:

# Initialize array
arr = [5, 2, 8, 7, 1]
temp = 0

# Sort the array in descending order
for i in range(0, len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] < arr[j]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp

# Displaying elements of array after sorting
print("Elements of array sorted in descending order: ")
for i in range(0, len(arr)):
print(arr[i], end=' ')



# Alternative method by using built-in sorted() method
print("Elements of array sorted in descending order: ", sorted(arr, reverse=True))

Output:

Elements of array sorted in descending order:
8 7 5 2 1