Python program to Sort an Array in Ascending and Descending order

Sorting of array in ascending and descending order using python

Sorting of array in ascending and descending order

Sorting can be done by using several algorithms. Sorting of array in ascending and descending order in Python can be done using sort() function. By using sort() function you can sort array into both ascending order and descending order by just using reverse=True or reverse=False

Example:

Input

  • size of array = 5
  • array= 3 9 4 8 1

Output

  • Ascending order = 1 3 4 8 9
  • Descending order = 9 8 4 3 1

Algorithm:

  • Input size of array.
  • Store it in some variable say n 
  • Input array say arr
  • Use arr.sort(reverse=False) or arr.sort() for ascending order of array.
  • Use arr.sort(reverse=True) for descending order of array

Sorting of array in ascending and descending order in Python can be done as follows

Python Code:

n=int(input(“Enter size of array\n))
arr=list(map(int,input(“Enter elements of array\n).split()))
arr.sort(reverse=False#arr.sort() also be used
print(“Ascending order array”)
print(*arr)
arr.sort(reverse=True)
print(“Descending order array”)
print(*arr)

Input:

Enter size of array
5
Enter elements of array
3 9 4 8 1

Output:

Ascending order array 
1 3 4 8 9
Descending order array
9 8 4 3 1