RUN

# Bubble Sort Program in Python

Written By -

Bubble sort is a simple sorting algorithm which compares the adjacent numbers in an array and swaps them if they are in the wrong order.

It is also referred to as a sinking sort.

In this program, we will learn to implement bubble sort in an array in order to sort the array in increasing order. Although the algorithm is simple but it is slow and impractical for some problems when it is compared to insertion sort.

Algorithm:

1. An array[arr] is initialized.
2. Length of the array is stored in a variable n.
3. For each value in array, a loop is generated.
4. For each value of the iteration from (3) a loop is generated excluding these many items because they are sorted towards the end.
5. Swap if a bigger number is encountered using a temporary variable “temp”.
6. Loop ends 4.
7. Loop ends 3.
8. Print the sorted array, which is in place of the original array now.
9. Exit

Code:

``````arr=[1,5,9,3,2,6]

n=len(arr)

for i in range(n):

for j in range(0,n-i-1):

if arr[j]>arr[j+1]:

temp=arr[j+1]

arr[j+1]=arr[j]

arr[j]=temp

print("Sorted Array : ", arr )``````

Output:

``Sorted Array : [1, 2, 3, 5, 6, 9]``

Related Posts:

Tutorials

Examples

Online Compilers

Interview Questions

Recent Articles