Python Program to find largest element in a array using bubble sort

March 3, 2022, Learn eTutorial

In this simple python program, we need to find the largest element. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What is a bubble sort?

In this python program, we need to find the largest element of the list using Bubble sort. So first, the list to be sorted, and then check the largest element from the sorted list. To get the list sorted, the bubble sort method is used.

Bubble sort: It is a most simple type of sort used but rarely used in the real world. It is also called a comparison sort. How it works is we have to take one element in the list and compare that with the adjacent element until the taken element is in the right position in the list.

In the second pass, we take the next element and compare that with adjacent elements to make that in the proper position. We continue that until the list is fully sorted. The worst-case complexity of bubble sort is O(n**2). where n is the number of elements in the list.

How we implement bubble sort and find the largest element using python?

Let us check the python program after initializing a list and With the help of a for loop, add the elements to the list using the append operator. Then open a nested for loop to implement the bubble sort as in the outer for loop we take each element from zero to the list's length. Using inner for loop we compare that element with all other elements in the list. With the help of a if condition statement in python programming, if the comparing element is greater than the compared element we do a swap using a temporary variable.


STEP 1: Initialize a list for storing the values in the list in python language.

STEP 2: Accept the number of terms needed in the user list using the input method in python.

STEP 3: Use a for loop and append operator in python programming to insert the entered elements to the list.

STEP 4: Start the outer for loop from zero to the length of the list to compare every element in the list.

STEP 5: Open the inner for loop from zero to one element less than the list's length.

STEP 6: With the help of an if condition compares, the element is higher than the adjacent element in the list.

STEP 7: Swap the element with the adjacent element using the swap method with the help of a temporary variable.

STEP 8: Print the last element of the list as the largest element in the list.

Python Source Code

n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
for i in range(0,len(a)):
    for j in range(0,len(a)-i-1):
print('Largest element in the list is:',a[n-1])


Enter number of elements: 5
Enter element: 12
Enter element: 14
Enter element: 5
Enter element: 7
Enter element: 2

Largest element in the list is: 14