• Rainy Season
• World
Monday - May 29, 2023

## 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: 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.
 Image Source ~ Crafted With Â©Ishwaranand – 2020 ~ Image by Â©Ishwaranand

### 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

Last updated on Sunday - May 21st, 2023

.