Question #112439

Start with an array of pointers to strings representing the days of the week, as found in

the PTRTOSTR program in this chapter. Provide functions to sort the strings into alphabetical

order, using variations of the bsort() and order() functions from the PTRSORT program

in this chapter. Sort the pointers to the strings, not the actual strings.

Expert's answer

#include <iostream>
#include <cstring>
#include <algorithm>

void sort(char **strings, int size);

int main() {
    const int DAYS = 7;
    char *arrptrs[DAYS] = {"Sunday", "Monday", "Tuesday",
                           "Wednesday", "Thursday",
                           "Friday", "Saturday"
    };
    sort(arrptrs, DAYS);
    for (auto &arrptr : arrptrs)
        std::cout << arrptr << " ";
    std::cout << std::endl;

    return 0;
}
void sort(char **strings, int size) {
    for (int i = 0; i < size - 1; ++i) {
        for (int j = i + 1; j < size; ++j) {
            if (std::strcmp(strings[i], strings[j]) > 0) {
                std::swap(strings[i], strings[j]);
            }
        }
    }
}
LATEST TUTORIALS
APPROVED BY CLIENTS