C++ Bubble Sort Algorithm

In this tutorial, we will learn how to write a bubble sort algorithm program using the C++ programming language.

C++ Bubble Sort Algorithm

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

Here is the C++ program for bubble sort algorithm:

#include <iostream>
#include <vector>

int main() {
    int n;
    bool swap_check = true;
    std::cout << "Enter the amount of numbers to sort: ";
    std::cin >> n;
    std::vector<int> numbers;
    std::cout << "Enter " << n << " numbers: ";
    int num;

    // Input
    for (int i = 0; i < n; i++) {
        std::cin >> num;
        numbers.push_back(num);
    }

    // Bubble Sorting
    for (int i = 0; (i < n) && (swap_check); i++) {
        swap_check = false;
        for (int j = 0; j < n - 1 - i; j++) {
            if (numbers[j] > numbers[j + 1]) {
                swap_check = true;
                std::swap(numbers[j],
                          numbers[j + 1]);  // by changing swap location.
                                            // I mean, j. If the number is
                                            // greater than j + 1, then it
                                            // means the location.
            }
        }
    }

    // Output
    std::cout << "\nSorted Array : ";
    for (int i = 0; i < numbers.size(); i++) {
        if (i != numbers.size() - 1) {
            std::cout << numbers[i] << ", ";
        } else {
            std::cout << numbers[i] << std::endl;
        }
    }
    return 0;
}

Output:

Enter the amount of numbers to sort: 5
Enter 5 numbers: 
10
30
20
50
40

Sorted Array : 10, 20, 30, 40, 50






Comments