Advertisements
Advertisements
Question
Write an algorithm for bubble sort with suitable example.
Advertisements
Solution
Here, DATA is a linear array with N elements. This algorithm sorts the elements of DATA in ascending order.
Step 1: Repeat steps 2 and 3 for K = 1 to N – 1
Step 2: Set Ptr: = 1
Step 3: Repeat while Ptr ≤ N – K
- If DATA[Ptr] > DATA[Ptr + 1], then interchange DATA[Ptr] and DATA[Ptr + 1]
- Set Ptr := Ptr + 1
Step 4: Exit
After N – 1 passes, all elements are sorted.
Example:
Consider a linear array of 5 elements:
Data[1] = 55
Data[2] = 43
Data[3] = 05
Data[4] = 06
Data[5] = 09
Pass 1:
55 > 43 → swap → 43 55 5 6 9
55 > 5 → swap → 43 5 55 6 9
55 > 6 → swap → 43 5 6 55 9
55 > 9 → swap → 43 5 6 9 55
The largest element, 55, moves to the last position.
Pass 2:
43 > 5 → swap → 5 43 6 9 55
43 > 6 → swap → 5 6 43 9 55
43 > 9 → swap → 5 6 9 43 55
Second largest element 43 moves to the correct position.
Pass 3:
5 < 6 → no swap
6 < 9 → no swap
Final sorted list:
5 6 9 43 55
After N – 1 passes, the array is sorted in ascending order.
