C++ Online Compiler
Example: Sort Names using Bubble Sort in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sort Names using Bubble Sort #include <iostream> // For input/output operations #include <vector> // For using std::vector to store names #include <string> // For using std::string objects int main() { // Step 1: Declare a vector of strings to store names std::vector<std::string> names; std::string name; int numNames; // Step 2: Get the number of names from the user std::cout << "Enter the number of names you want to sort: "; std::cin >> numNames; std::cin.ignore(); // Consume the newline character // Step 3: Read names from the user std::cout << "Enter " << numNames << " names:\n"; for (int i = 0; i < numNames; ++i) { std::cout << "Name " << i + 1 << ": "; std::getline(std::cin, name); names.push_back(name); } // Step 4: Implement Bubble Sort algorithm // Outer loop for passes for (int i = 0; i < numNames - 1; ++i) { // Inner loop for comparisons and swaps for (int j = 0; j < numNames - 1 - i; ++j) { // Compare adjacent names. If names[j] is alphabetically greater than names[j+1], swap them. if (names[j] > names[j+1]) { // Swap using a temporary string std::string temp = names[j]; names[j] = names[j+1]; names[j+1] = temp; } } } // Step 5: Print the sorted names std::cout << "\nNames in alphabetical order:\n"; for (const std::string& sortedName : names) { std::cout << sortedName << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS