Python Program to Sort Array in Ascending Order

Write a Python Program to sort Numpy Array items in Ascending order. The sort function in the numpy module sorts the array items in ascending order.

import numpy as np

orarr = np.array([11, 55, 99, 22, 7, 35, 70])
print("***Sorting Numpy Array in Ascending Order***")
print("Original Array = ", orarr)

orarr.sort()
print("sorted Array   = ", orarr)
Python Program to Sort Array in Ascending Order

Python Program to Sort Array in Ascending Order using the For Loop

In this example, we used the Nested for loop range to sort the numpy array items in ascending order. Within the loop, the if statement (if (orarr[i] > orarr[j])) compares each item with other array items and assigns them to the temp variable. 

import numpy as np

orarr = np.array([33, 4, 76, 98, 2, 88, 17, 122, 61])
print("***Sorting Numpy Array in Ascending Order***")
print("Original Array           = ", orarr)

length = len(orarr)

for i in range(length):
    for j in range(i + 1, length):
        if (orarr[i] > orarr[j]):
            temp = orarr[i]
            orarr[i] = orarr[j]
            orarr[j] = temp

print("Array in Ascending Order = ", orarr)

Sorting Numpy Array Items in ascending order using for loop output

***Sorting Numpy Array in Ascending Order***
Original Array           =  [ 33   4  76  98   2  88  17 122  61]
Array in Ascending Order =  [  2   4  17  33  61  76  88  98 122]

In this Python Numpy Array example program, we created a function (arrayReverse(orarr)) that sorts the array items in ascending order.

# using for loop and functions

import numpy as np

def arrayReverse(orarr):
    length = len(orarr)

    for i in range(length):
        for j in range(i + 1, length):
            if (orarr[i] > orarr[j]):
                temp = orarr[i]
                orarr[i] = orarr[j]
                orarr[j] = temp

orarr = np.array([22, 17, 68, 55, 19, 99, 58, 77])
print("***Sorting Numpy Array in Ascending Order***")
print("Original Array           = ", orarr)

arrayReverse(orarr)
print("Array in Ascending Order = ", orarr)

Sorting Numpy Array Items in ascending order output

***Sorting Numpy Array in Ascending Order***
Original Array           =  [22 17 68 55 19 99 58 77]
Array in Ascending Order =  [17 19 22 55 58 68 77 99]