Array Sorting: How to sort an array of integers in Python3?

ARRAY SORTING in Python

Array sorting can be of two types:

  • Ascending Order Sorting: The arrangement of elements of the array is from smallest to largest number.
  • Descending Order Sorting: The arrangement of elements of the array is from largest to smallest number.

There are a lot of algorithms through which we can do the sorting. The image below is an example of insertion sort.

Sorting in Python

Image Source: Geeksforgeek

The sorting in python is easy, as there’s a built-in¬†function sort(), which directly sorts the elements of a list(array).

The code snippet is given below:

PROGRAM:

print("Input Array Elements:")
l=list(map(int,input().split(" ")))
l.sort()
a=[0 for i in range(len(l))]
print("Input your choice:")
print("1.Arrange the Array in Ascending Order")
print("2.Arrange the Array in Descending Order")
c=int(input("Choice(1/2):"))
if(c==1):
    for i in range(len(l)):
        print(l[i],end=" ")
elif(c==2):
    for i in range(len(l)):
        a[len(l)-1-i]=l[i]
    for i in range(len(a)):
        print(a[i],end=" ")
else:
    print("Choose either 1 or 2.")

OUTPUT 1:



Input Array Elements:
4 5 6 2 1 5 7 9 8 2 6 8 9
Input your choice:
1.Arrange the Array in Ascending Order
2.Arrange the Array in Descending Order
Choice(1/2):2
9 9 8 8 7 6 6 5 5 4 2 2 1

OUTPUT 2:

Input Array Elements:
45 65 87 21 54 69 40 32 78 98 75
Input your choice:
1.Arrange the Array in Ascending Order
2.Arrange the Array in Descending Order
Choice(1/2):1
21 32 40 45 54 65 69 75 78 87 98

Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *