# Bubble sort program in Python

Written by

## How Bubble sort works ?

**Bubble sort is a simple sorting algorithm that 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:**

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

**Code for bubble sort python:**

`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]`