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

3 comments on “Python program to Sort an Array in Ascending and Descending order”


  • Riya

    from typing import List
    size = int(input(“enter the size of array”))
    arr: List[int] = []
    for i in range(size):
    element = int(input())
    arr.append(element)
    arr.sort()
    print(“Ascending form of array:”, *arr)
    arr.sort(reverse=False)
    print(“Descending form of array:”, *arr)


  • Nikita

    def ascending(arr):
    for i in range(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
    return arr

    def descending(arr):
    for i in range(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
    return arr

    arr = [5, 4, 2, 3, 7, 2, 1, 22, 33, 6, 7, 88, 76, 54]
    print(ascending(arr))
    print(descending(arr))


  • 44_Harsh

    size = int(input(‘enter size of an array : ‘))
    arr = []
    for i in range(size):
    element = int(input(“enter element in array :”))
    arr.append(element)
    arr.sort()
    print(“sorted array in ascending order is : “,arr)
    print(“sorted array in descending order is : “,arr[::-1])
    #OUTPUT
    enter size of an array : 3
    enter element in array :9
    enter element in array :7
    enter element in array :6
    sorted array in ascending order is : [6, 7, 9]
    sorted array in ascending order is : [9, 7, 6]