Description: Bubble sort is one of the simplest sorting algorithms. It works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. This process is repeated until the list is sorted. The name "bubble sort" comes from the way smaller elements "bubble" to the top (beginning) of the list.
Here's a C++ implementation of bubble sort:
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
bool swapped; // Flag to check if a swap was made
for (int i = 0; i < n - 1; i++) {
swapped = false; // Reset swap flag for this pass
for (int j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]); // Swap if they're in the wrong order
swapped = true; // Mark that a swap has occurred
}
}
// If no swaps occurred, the array is already sorted
if (!swapped)
break;
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
bubbleSort function takes an array and its size as parameters.swapped flag tracks whether any swaps were made during a pass. If no swaps occur, the array is already sorted, and the loop can exit early.Bubble sort is a straightforward algorithm that is easy to understand and implement. However, its time complexity makes it inefficient for large datasets compared to more advanced sorting algorithms like quick sort or merge sort. Despite its simplicity, bubble sort is often used in educational contexts to introduce sorting concepts.
Open this section to load past papers