Bubble Sort Algorithm for Sorting Strings in C++

In this exercise, you will implement the Bubble Sort algorithm to sort an array of strings alphabetically. Bubble Sort is a simple comparison-based sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The process is repeated until the list is sorted. While it is easy to implement, Bubble Sort has an average and worst-case time complexity of O(n^2), making it less efficient for large datasets. This exercise will help you understand the concept of sorting using comparisons and provide a practical implementation for sorting strings in C++.

Group

Search and Sort Algorithms in C++

Objective

Write a C++ function to sort an array of strings alphabetically using the Bubble Sort algorithm. The function should compare adjacent strings and swap them if they are in the wrong order, repeating the process until the entire array is sorted.

Create a function that sorts strings alphabetically using the Bubble Sort method.

Example C++ Exercise

 Copy C++ Code
#include <iostream>  // Include the input-output stream library
#include <string>     // Include the string library for handling strings
#include <vector>     // Include the vector library to use dynamic arrays
using namespace std;

// Function to perform Bubble Sort on an array of strings
void bubbleSort(vector<string> &arr) {
    int n = arr.size();  // Get the size of the array

    // Outer loop to traverse through all elements
    for (int i = 0; i < n - 1; i++) {
        // Inner loop for comparison and swapping adjacent elements
        for (int j = 0; j < n - i - 1; j++) {
            // Compare adjacent strings
            if (arr[j] > arr[j + 1]) {
                // Swap the strings if they are in the wrong order
                string temp = arr[j];  // Temporary variable for swapping
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    // Define an array of strings
    vector<string> arr = {"Banana", "Apple", "Orange", "Mango", "Peach"};

    // Call the bubbleSort function to sort the array
    bubbleSort(arr);

    // Display the sorted array
    cout << "Sorted array: ";
    for (const string &str : arr) {
        cout << str << " ";  // Print each string in the sorted array
    }
    cout << endl;

    return 0;
}

 Output

Sorted array: Apple Banana Mango Orange Peach

Share this C++ Exercise


More C++ Programming Exercises of Search and Sort Algorithms in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.