Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The process is repeated until the list is sorted.
Program Structure
#include using namespace std; /** * Function to implement bubble sort algorithm. * * @param arr The array to be sorted. * @param n The number of elements in the array. */ void bubbleSort(int arr[], int n) { for (int i = 0; i < n-1; i++) { // Flag to check if any swapping happened bool swapped = false; // Last i elements are already sorted for (int j = 0; j < n-i-1; j++) { // Compare adjacent elements if (arr[j] > arr[j+1]) { // Swap if they are in the wrong order swap(arr[j], arr[j+1]); swapped = true; } } // If no two elements were swapped by inner loop, then break if (!swapped) { break; } } } /** * Function to print an array. * * @param arr The array to be printed. * @param n The number of elements in the array. */ void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; } /** * Main function to execute the bubble sort algorithm. */ int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Unsorted array: \n"; printArray(arr, n); bubbleSort(arr, n); cout << "Sorted array: \n"; printArray(arr, n); return 0; }
Explanation
The C++ program consists of the following components:
- Header Files: The program includes the
iostream
library to facilitate input and output operations. - Function
bubbleSort
: This function takes an array and its size as parameters. It uses two nested loops to compare and swap adjacent elements if they are out of order. A boolean flag,swapped
, is used to optimize the algorithm by terminating early if no swaps occur during an inner loop iteration. - Function
printArray
: This function prints the elements of the array. It is called before and after sorting to display the unsorted and sorted arrays. - Function
main
: This is the entry point of the program. It initializes an array, prints the unsorted array, calls thebubbleSort
function, and finally prints the sorted array.
Output
The program will output the following:
Unsorted array: 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90