C++ Online Compiler
Example: Sort String Descending with Bubble Sort in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sort String Descending with Bubble Sort #include <iostream> #include <string> // Required for std::string #include <algorithm> // Required for std::swap using namespace std; int main() { // Step 1: Initialize the string string myString = "coding"; cout << "Original string: " << myString << endl; // Step 2: Implement Bubble Sort for descending order int n = myString.length(); // 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) { // Compare adjacent characters. // If the current character is less than the next, swap them. // This 'bubbles up' larger characters towards the beginning. if (myString[j] < myString[j+1]) { std::swap(myString[j], myString[j+1]); } } } // Step 3: Print the sorted string cout << "Sorted string (descending): " << myString << endl; return 0; }
Output
Clear
ADVERTISEMENTS