C++ Online Compiler
Example: Bubble Sort using Array in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Bubble Sort using Array #include <iostream> #include <vector> // Using vector for flexibility, dynamic array behavior #include <algorithm> // For std::swap // Function to print the array elements void printArray(const std::vector<int>& arr) { for (int x : arr) { std::cout << x << " "; } std::cout << std::endl; } int main() { // Step 1: Initialize an unsorted array (using std::vector as a dynamic array) std::vector<int> arr = {64, 34, 25, 12, 22, 11, 90}; int n = arr.size(); std::cout << "Original array: "; printArray(arr); // Step 2: Implement Bubble Sort algorithm // Outer loop controls the number of passes for (int i = 0; i < n - 1; ++i) { bool swapped = false; // Flag to optimize: if no swaps in a pass, array is sorted // Inner loop for comparisons and swaps within each pass // The last 'i' elements are already in place, so we don't need to check them for (int j = 0; j < n - 1 - i; ++j) { // Compare adjacent elements if (arr[j] > arr[j + 1]) { // Swap if elements are in the wrong order (for ascending sort) std::swap(arr[j], arr[j + 1]); swapped = true; // Mark that a swap occurred } } // If no two elements were swapped by inner loop, then the array is sorted if (!swapped) { break; } } // Step 3: Print the sorted array std::cout << "Sorted array: "; printArray(arr); return 0; }
Output
Clear
ADVERTISEMENTS