# Bubble Sort Algorithm in Array

Bubble Sort Algorithm in Array is part of Learning Data Structure Series. In the previous article of Binary Search Algorithm in Array we learnt to locate an element in an array with Divide-n-Conquer method.

In this article we will learn to execute Bubble Sort Algorithm in Array.

Sorting refers to the process of rearranging the element in a logical order. There are various sorting algorithm available like Bubble Sort, Insertion Sort, Selection Sort, Merge Sort etc. Among them Bubble Sort Algorithm in Array is the simplest sorting algorithm.

Bubble sort arranges the element in increasing order. It Bubbles up the largest element to its correct location first. In next phase it places second largest element to its correct location and so on.

## Bubble Sort Algorithm in Array

**BUBBLE(DATA,N)**

```
1. Set PTR:=1
2. Repeat steps 2 & 3 for I=1 to N-1
3. Repeat while PTR<=N-I
a. If DATA[PTR]>DATA[PTR+1] then:
TEMP:=DATA[PTR]
DATA[PTR]:=DATA[PTR+1]
DATA[PTE+1]:=TEMP
[End If]
b. Set PTR:=PTR+1
[End While Loop]
[End For Loop]
4. Exit
```

In this algorithm DATA is array with N elements. So maximum no of passes required to sort the array will be N-1. The outer loop is controlling the passes. PTR is a variable which controls the inner loop. In inner loop, we compare the elements and interchange them if required.

Let us understand it by example. Let DATA be an array having 4 elements. So we will require at the most 3 passes to sort the array.

Index | 1 | 2 | 3 | 4 |

Value | 60 | 50 | 30 | 10 |

**Pass 1:**

Index | 1 | 2 | 3 | 4 |

Value | 60 | 50 | 30 | 10 |

→ | ← |

Index | 1 | 2 | 3 | 4 |

Value | 50 | 60 | 30 | 10 |

→ | ← |

Index | 1 | 2 | 3 | 4 |

Value | 50 | 30 | 60 | 10 |

→ | ← |

Index | 1 | 2 | 3 | 4 |

Value | 50 | 30 | 10 | 60 |

**Pass 2:**

Index | 1 | 2 | 3 | 4 |

Value | 50 | 30 | 10 | 60 |

→ | ← |

Index | 1 | 2 | 3 | 4 |

Value | 30 | 50 | 10 | 60 |

→ | ← |

Index | 1 | 2 | 3 | 4 |

Value | 30 | 10 | 50 |
60 |

**Pass 3:**

Index | 1 | 2 | 3 | 4 |

Value | 30 | 10 | 50 |
60 |

→ | ← |

Index | 1 | 2 | 3 | 4 |

Value | 10 |
30 |
50 |
60 |

Result:-

Index | 1 | 2 | 3 | 4 |

Value | 10 |
30 |
50 |
60 |

In the series of Learning Data Structure, sorting algorithms continue with Insertion Sort Algorithm in Array as our next article. Insertion Sort identifies the smallest element first and inserts it into the correct location followed by second smallest element in the array.