Sorting an Array using Python

Sorting an Array

In this program we need to sort the given array in ascending order such that element will be arranged from smallest to largest. We can sort an array using two loops or in-built function in Python. The outer loop will select an element and inner loop allow us to compare and select element with rest of the element.

Example:

• Orignal Array: 7 5 4 2 3
• Array after sorting: 2 3 4 5 7

WORKING:

• Declare and intialize an array
• Loop through the array and select an element.
• The inner loop will be used to compare the selected element from the outer loop with rest of the elemnts of the array.
• If any element is less than the selected element then swap the value.

Python Code:

#intalize array
ar=[7,5,3,4,2
#displaying array in the orginal list
print(‘Orginal array:’)
for i in range(0,len(ar)):
print(ar[i],end=‘ ‘

#sort the array in ascending order
for i in range(0,len(ar)):
for j in range(i+1,len(ar)):
if(ar[j]<ar[i]): #comparing
#swapping the value if the condition holds true
ar[i],ar[j]=ar[j],ar[i]

#displaying the sorted array
print()
print(*ar,sep=‘ ‘)
Output:

Orginal array:

7 5 3 4 2

2 3 4 5 7