Bubble Sort Python | Ascending and Descending order

Bubble Sort algorithm and implementation have been discussed in this post. The bubble sort algorithm has been implemented using python in the below. It is also important to know about the time complexity of this sorting algorithm. To know the bubble sort time complexity, please read the post which is available in this link.

Bubble Sort in Python (Ascending order) : 

n=int(input())
DataArray=list(map(int, input().split()))
print(DataArray[0])
for i in range(0, n):
for j in range(0, n-1):
if DataArray[j+1] < DataArray[j]:
temp=DataArray[j]
DataArray[j]=DataArray[j+1]
DataArray[j+1]=temp
print('Bubble sorting in ascending order: ', DataArray)

Sample Input:
5
4 3 1 5 2

Sample Output:
Bubble sorting in ascending order: [1, 2, 3, 4, 5]

Bubble Sort in Python (Descending order) : 
n=int(input())
DataArray=list(map(int, input().split()))
print(DataArray[0])
for i in range(0, n):
for j in range(0, n-1):
if DataArray[j+1] > DataArray[j]:
temp=DataArray[j]
DataArray[j]=DataArray[j+1]
DataArray[j+1]=temp
print('Bubble sorting in descending order: ', DataArray)

Sample Input: 
5
4 3 1 5 2
Sample Output:
Bubble sorting in ascending order: [5, 4, 3, 2, 1]

Post a Comment

Previous Post Next Post