Python Program to sort the elements of an array

Python Program to Sort the elements of an array

Python Program to sort the elements of an array

In this section we will learn how sort the elements of an array, there are two ways to sort array ascending order or descending order.
In ascending the we start from small element and goes to the largest element entered by the user and In descending order we start from largest element and goes to the smaller element input given by the user.
As shown in image you can better understand sorting and below we will provide Algorithm and Python code.

Algorithm for sorting the elements of  an array in Ascending order

  • STEP 1: First declare and initialize an array.
  • STEP 2: Iterate the loop through the array and select an element.
  • STEP 3: The inner loop will be used to compare the selected element from the outer loop with the rest of the elements of the array.
  • STEP 4: If any element is smaller than the selected element then swap the values.
  • STEP 5: Continue this process till entire array is sorted in ascending order.

Algorithm for sorting the elements of  an array in Descending order

  • STEP 1: First declare and initialize an array.
  • STEP 2: Iterate the loop through the array and select an element.
  • STEP 3: Inner loop will be used to compare selected element from the outer loop with the rest of the elements of the array.
  • STEP 4: If any element is greater than the selected element then swap the values.
  • STEP 5: Continue this process till the entire list is sorted in descending order.

Sort the elements of an array using Python concept

size=int(input("ENTER ARRAY SIZE"))

arr=[]

for i in range(size):

    element=int(input())

    arr.append(element)

print("ASCENDING ORDER OF ARRAY")

arr.sort()

print(*arr)

print("DESCENDING ORDER OF ARRAY")

arr.sort(reverse=True)

print(*arr)
Output
ENTER ARRAY SIZE5
4  24  9  5  1 
ASCENDING ORDER OF ARRAY
1  4  5  9  25
DESCENDING ORDER OF ARRAY
25  9  5  4  1