Algorithm and Example of Bubble Sort
Bubble Sort
Q) Explain the Bubble sort algorithm with a suitable example
- Bubble sort is one of the simplest and most popular sorting methods.
- This sort is based on comparing two adjacent elements, say, data[x]and data[x+1].if data[x]>data[x+1]then they are exchanged.
- To sort N elements bubble sort takes(N-1)passes.
Pass 1: Bubble Sort Largest element is stored in are Data[N] position.
Pass 2: Second largest element stored are Data[N-1] position
Pass 3: Third largest element is stored in are Data[N-2] position.
.
.
Pass N-1: Data[1] and Data[2]are sorted, so that Data[1], Data[2]β¦Data[N] are sorted.

Algorithm:bubble_sort (Data[],N)
- This is the algorithm for bubble sort to sort the array in ascending order.
- Data[]-Array of elements
- N-size of array
- i,j-index variable
- temp-temporary variable
Step 1 : Start
Step 2 : Repeat steps 3 and 4 for j = 1 to (N-1)
Step 3 : Repeat step 4 for j=1 to (N-1)
Step 4 : If Data [i] > Data[j+1] then
Β Β Β Β Β Β Β [ Exchange Data[j] & Data[j+1] ]
Β Β Β Β Β Β Β a) Set temp = Data[j]
Β Β Β Β Β Β Β b) Set Data[j] = Data[j+1]
Β Β Β Β Β Β Β c) Set Data[j+1] = temp
Step 5 : Stop
ExampleΒ Bubble Sort
Consider an array containing 5 elements.
Given array is A =
42 | 23 | 74 | 65 | 11 |
---|
Pass 1 Initial Array
42 | 23 | 23 | 23 | 23 |
---|---|---|---|---|
23 | 42 | 42 | 42 | 42 |
74 | 74 | 74 | 65 | 65 |
65 | 65 | 65 | 74 | 11 |
11 | 11 | 11 | 11 | 74 |
Pass 2 Initial Array
23 | 23 | 23 | 23 |
---|---|---|---|
42 | 42 | 42 | 42 |
65 | 65 | 65 | 11 |
11 | 11 | 11 | 65 |
74 | 74 | 74 | 74 |
Pass 3 Initial Array
23 | 23 | 23 |
---|---|---|
42 | 42 | 11 |
11 | 11 | 42 |
65 | 65 | 65 |
74 | 74 | 74 |
Pass 4 Initial Array
23 | 11 |
---|---|
11 | 23 |
42 | 42 |
65 | 65 |
74 | 74 |
Result: Given array is sorted in 4 Passes.
11 | 22 | 42 | 65 | 74 |
---|