samedi 9 novembre 2019

Sorting given text alphabetically w/o additional library

My homework was to write an application that sorts given text in alphabetically order. To do so, I was allowed only to use 'vector', 'string' and 'iostream' library.

I succeed but now struggling with strange problem - while I'm trying to sort a short text, everything works well but with longer inputs program seems to get into infinity loop or efficiency problem. Eg in text

"Albert Einstein 14 March 1879 – 18 April 1955 was a German-born theoretical physicist who developed the theory of relativity one of the two pillars of modern physics alongside quantum mechanics His work is also known[...]" 

everything works great until "mechanics" phrase. After adding this, or any other word, program is running eternally like I mentioned before.

I'm afraid that I have to paste whole code in this case (please forgive).

#include <iostream>
#include <string>
#include <vector>

int compare(std::string first, std::string second){
    int flag = 1;
    int i;
    if (first.size() <= second.size()){
        for (i = 0; i<first.size(); ++i ){
            if (first[i] == second[i]){
                continue;}
            else if (first[i] > second[i]){
                flag = 0;
                break;}
            else {
                break;}}}
    else {
        for (i = 0; i<second.size(); ++i ){
            if (first[i] == second[i]) {
                continue;}
            else if (first[i] > second[i]){
                flag = 0;
                break;}
            else {
                break;}
        }
        int m = second.size() - 1;
        if (first[m] == second[m]){
                flag = 0;}}
return flag;}


int main() {
    std::vector<std::string> text;
    std::string word;
    std::string tmp;
    while(std::cin >> word){
        text.push_back(word);}
    int mistakes, m = 1;
    while(m) {
        mistakes = 0;
        for (int index = 1; index < text.size() ; ++index){
            if (!(compare(text[index-1], text[index]))){
                tmp = text[index];
                text[index] = text[index-1];
                text[index-1] = tmp;
                mistakes += 1;}}
        m = mistakes;}
    for (auto element: text){
        std::cout << element << " ";}}

I would love to hear how to fix it and why exactly this problem appears - at least time of execution doesn't grow with lenght of input, but more like "work/doesn't work", what is unlike to efficency issues.

Aucun commentaire:

Enregistrer un commentaire