How to sort an array of strings in lexicographical (dictionary) order in C++

1 Answer

0 votes
#include <iostream>
#include <string>
 
void sort(std::string s[], int rows) {
    std::string tmp;
    
    for (int i = 0; i < rows - 1; i++) {
        for (int j = i + 1; j < rows; j++) {
            if (s[i] > s[j]) {
                tmp = s[i];
                s[i] = s[j];
                s[j] = tmp;
            }
        }
    }
}

int main()
{
    std::string s[] = { "c#", "c++", "c", "php", "java" };
 
    int rows = sizeof(s) / sizeof(*s);
 
    sort(s, rows);
 
    for (int i = 0; i < rows; i++) {
        std::cout << s[i] << std::endl;
    }
}
 
 
 
/*
run:
 
c
c#
c++
java
php
 
*/

 



answered May 24, 2017 by avibootz
edited Jul 27, 2024 by avibootz
...