CSC211 ยท 2074 ยท 5 marks
What do you mean by sorting? Explain the Bubble sort with example.
What do you mean by sorting? Explain the Bubble sort with example. [5]
Quick answer
Sorting is the process of arranging data elements in a specific order (either ascending or descending) so that the data can be searched, accessed, or processed more efficiently. Sorting organizes a collection of data into a sequence ordered by some criterion.
Sorting and Bubble Sort
What is Sorting?
Example: Arranging [5, 2, 8, 1, 9] into [1, 2, 5, 8, 9] (ascending order).
Bubble Sort
Definition: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. The basic idea is to pass through the array sequentially several times. Each pass consists of comparing each element a[i] with its adjacent element a[i+1] and interchanging them if they are not in proper order.
After each pass, the largest unsorted element "bubbles up" to its correct position at the end of the array.
Algorithm
for i = 0 to n-2:
for j = 0 to n-2-i:
if a[j] > a[j+1]:
swap(a[j], a[j+1])
Time Complexity
| Case | Complexity |
|---|---|
| Best Case | O(n^2) |
| Average Case | O(n^2) |
| Worst Case | O(n^2) |
Worked Example
Array: [5, 3, 8, 1, 4]
Pass 1 (i = 0)
| Step | Comparison | Array State |
|---|---|---|
| j=0 | 5 > 3? Yes, swap | [3, 5, 8, 1, 4] |
| j=1 | 5 > 8? No | [3, 5, 8, 1, 4] |
| j=2 | 8 > 1? Yes, swap | [3, 5, 1, 8, 4] |
| j=3 | 8 > 4? Yes, swap | [3, 5, 1, 4, 8] |
Largest element 8 is now at its correct position.
Pass 2 (i = 1)
| Step | Comparison | Array State |
|---|---|---|
| j=0 | 3 > 5? No | [3, 5, 1, 4, 8] |
| j=1 | 5 > 1? Yes, swap | [3, 1, 5, 4, 8] |
| j=2 | 5 > 4? Yes, swap | [3, 1, 4, 5, 8] |
Second largest element 5 is now at its correct position.
Pass 3 (i = 2)
| Step | Comparison | Array State |
|---|---|---|
| j=0 | 3 > 1? Yes, swap | [1, 3, 4, 5, 8] |
| j=1 | 3 > 4? No | [1, 3, 4, 5, 8] |
Pass 4 (i = 3)
| Step | Comparison | Array State |
|---|---|---|
| j=0 | 1 > 3? No | [1, 3, 4, 5, 8] |
Final Sorted Array
[1, 3, 4, 5, 8]
Summary
- Bubble sort is simple but inefficient for large datasets due to O(n^2) complexity.
- It performs a maximum of n-1 passes for an array of n elements.
- It is an in-place sorting algorithm (no extra memory required).
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.