- Asked 2/14
- 2068 Bhadra · 3 marks
- 2068 Magh · 3 marks
Algorithm for an exchange sort
Short answer
Bubble sort repeatedly scans the array, comparing adjacent elements and swapping them if out of order. After each pass the largest unsorted element bubbles to its correct end position. Complexity is O(n²) average/worst, O(n) best if early stop is used.
Write an algorithm for any one of the exchange sort (any sorting algorithm of your choice).
Bubble sort is an exchange sort. It repeatedly compares adjacent elements and exchanges them if they are out of order. After each pass the largest remaining element "bubbles" to the end.
Algorithm
BubbleSort(a[0..n-1])
1. for pass = 1 to n-1
2. swapped = 0
3. for i = 0 to n-pass-1
4. if a[i] > a[i+1]: swap a[i], a[i+1]; swapped = 1
5. if swapped = 0: stop (already sorted)
C code
void bubble_sort(int a[], int n) {
int pass, i, t, swapped;
for (pass = 1; pass < n; pass++) {
swapped = 0;
for (i = 0; i < n - pass; i++) {
if (a[i] > a[i + 1]) { /* exchange */
t = a[i]; a[i] = a[i + 1]; a[i + 1] = t;
swapped = 1;
}
}
if (!swapped) break; /* no exchange: sorted */
}
}
Trace for 5 3 8 1
| Pass | Array after pass |
|---|---|
| 0 | 5 3 8 1 |
| 1 | 3 5 1 8 |
| 2 | 3 1 5 8 |
| 3 | 1 3 5 8 |
Complexity: worst and average O(n²), best O(n) (already sorted, with the swapped flag). It is stable and in-place, using O(1) extra space.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Stable vs unstable sorting; heap · Data Structure and Algorithm, chapter 7
- Radix sort definition and algorithm · Data Structure and Algorithm, chapter 7
- Merge sort algorithm and trace · Data Structure and Algorithm, chapter 7
- Heap sort with example · Data Structure and Algorithm, chapter 7
- Merge and radix sort on 142, 523, ... · Data Structure and Algorithm, chapter 7
- Radix sort on 25, 57, 48, 37, ... · Data Structure and Algorithm, chapter 7
- Remez exchange algorithm with flow chart · Digital Signal Analysis and Processing, chapter 5 · asked 4×
- Need for non-uniform quantization; one algorithm · Communication Systems, chapter 4
- Optimum filter; Remez exchange expression · Digital Signal Analysis and Processing, chapter 5 · asked 5×
- Nepal Airlines jet plane choice, 4 years and infinite · Engineering Economics, chapter 4