C++ Online Compiler
Example: Bubble Sort in Descending Order in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Bubble Sort in Descending Order #include <iostream> #include <vector> #include <algorithm> // Required for std::swap using namespace std; // Function to perform bubble sort in descending order void bubbleSortDescending(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 for (int j = 0; j < n - i - 1; ++j) { // If current element is smaller than the next, swap them // This ensures larger elements 'bubble up' to the left if (arr[j] < arr[j+1]) { swap(arr[j], arr[j+1]); } } } } // Function to print the array void printArray(const vector<int>& arr) { for (int x : arr) { cout << x << " "; } cout << endl; } int main() { // Step 1: Initialize an unsorted array vector<int> numbers = {64, 34, 25, 12, 22, 11, 90}; cout << "Original array: "; printArray(numbers); // Step 2: Apply bubble sort in descending order bubbleSortDescending(numbers); // Step 3: Print the sorted array cout << "Sorted array (descending): "; printArray(numbers); return 0; }
Output
Clear
ADVERTISEMENTS