Bubble Sort Algorithm Implementation in C++

This C++ exercise demonstrates the implementation of the Bubble Sort algorithm, a fundamental sorting technique used to order elements in a list. Bubble Sort works by repeatedly stepping through the array, comparing adjacent elements, and swapping them if they are in the wrong order. The process continues until the array is fully sorted. This example is designed to help you understand how iterative sorting works, especially useful for beginners learning algorithm fundamentals and nested loop logic. The final result is a sorted array displayed in ascending order.

Group

Search and Sort Algorithms in C++

Objective

1. Create a function named bubbleSort that takes an array and its size as parameters.
2. Implement the Bubble Sort logic using nested loops to repeatedly compare and swap adjacent elements if needed.
3. In the main function, define an array of integers and display it before and after sorting.
4. Use standard output to show the array's state before and after applying the sorting algorithm.

Implement the Bubble Sort algorithm.

Example C++ Exercise

 Copy C++ Code
#include <iostream>     // Include for input and output operations
using namespace std;

// Function to perform Bubble Sort on an array
void bubbleSort(int arr[], int n) {
    // Outer loop controls the number of passes
    for (int i = 0; i < n - 1; i++) {
        // Inner loop compares adjacent elements and swaps them if necessary
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap elements if they are in the wrong order
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

// Function to print the elements of the array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    // Define an array of integers to be sorted
    int data[] = {64, 34, 25, 12, 22, 11, 90};
    int size = sizeof(data) / sizeof(data[0]); // Calculate the number of elements

    // Display the original array
    cout << "Original array: ";
    printArray(data, size);

    // Call the bubbleSort function to sort the array
    bubbleSort(data, size);

    // Display the sorted array
    cout << "Sorted array: ";
    printArray(data, size);

    return 0;   // End of program
}

 Output

Original array: 64 34 25 12 22 11 90 
Sorted array: 11 12 22 25 34 64 90 

Share this C++ Exercise


More C++ Programming Exercises of Search and Sort Algorithms in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.