Tuesday, January 4, 2022

How to sort the elements of an Array using bubble sorting method in Python Program

Python Program to sort elements of an Array in ascending order using bubble sort technique
In 'bubble sort' technique, all the 'n' elements from 0 to n are considered and then we check the first element of array say ary[ j ]  will be compared with the next element ary[ j+1 ], ary[j+1] will be compared with ary[ j+2 ] and so on.
if ary[ j ] is greater than ary[ j+1] then those two elements will be swapped or interchanged, as we are doing the sort order in Ascending. When two elements are swapped, the no. of elements to be sorted becomes lesser by 1.

Lets understanding the bubble sorting method using the following program. In this program we used the 'flag1' which becomes True when there is a swapping happened between elements, otherwise the 'flag1' will becomes False.

# Importing Array
from array import*
ary1 = array('i', [])  #blank array declaration to store elements

print('How many elements to store: ', end='')
# accept the input into n
n = int(input())

# adding elements to array
for i in range(n):
    print('Enter element{}: '.format(i+1))
    ary1.append(int(input()))
print('The original array is:', ary1)

# bubble sorting array elements in ascending order
flag1 = False # when swap is done , flag1 becomes True
j = 0
for i in range(n-1):
    for j in range((n-1)-i):
        # swapping/soring the numbers
        if ary1[j] > ary1[j+1]:
            k = ary1[j]
            ary1[j] = ary1[j+1]
            ary1[j + 1] = k
            flag1 = True
    if flag1 == False:
        break
    else:
        flag1 = False
print('The array with sorted elements is: ', ary1)

# ------------------------------------------------------------------------------------------------------------------------ #
Input:
How many elements to store: 5
Enter element1: 
4
Enter element2: 
2
Enter element3: 
5
Enter element4: 
3
Enter element5: 
1

Ouput:
The original array is: array('i', [4, 2, 5, 3, 1])
The array with sorted elements is:  array('i', [5, 4, 3, 2, 1])
Process finished with exit code 0
#--------------------------------------------------------------Thanks--------------------------------------------------------------#

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.