C++ Online Compiler
Example: Basic Bubble Sort Algorithm in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Basic Bubble Sort Algorithm #include <iostream> #include <vector> // Using vector for dynamic arrays, but can also use fixed-size arrays #include <algorithm> // For std::swap void printArray(const std::vector<int>& arr) { for (int num : arr) { std::cout << num << " "; } std::cout << std::endl; } void bubbleSort(std::vector<int>& arr) { int n = arr.size(); // Outer loop for passes for (int i = 0; i < n - 1; ++i) { // Inner loop for comparisons and swaps // (n-1-i) because the last 'i' elements are already in place for (int j = 0; j < n - 1 - i; ++j) { // Compare adjacent elements if (arr[j] > arr[j + 1]) { // Swap them if they are in the wrong order std::swap(arr[j], arr[j + 1]); } } } } int main() { std::vector<int> numbers = {5, 1, 4, 2, 8}; std::cout << "Original array: "; printArray(numbers); bubbleSort(numbers); std::cout << "Sorted array (Basic Bubble Sort): "; printArray(numbers); return 0; }
Output
Clear
ADVERTISEMENTS