Define a function

string sort(string s)

that returns a string with the same characters as s, but arranged in ascending order, according to ascii value . For example sort("hello") will return the string "ehllo". Notice that the function returns a different string from the original argument, since s is not passed by reference.

Use the following algorithm: Initialize a temporary variable t to the empty string . Now find minIndex: the index of the smallest character c in s. Append s[minIndex] to t and then call s.erase(minIndex, 1). Repeat this process until s is empty. Return t.

Here is my solution:

string sort(string s)
{
    string t = "";
    char c;
    int minIndex = 0;
    for(int i = 0; i < s.length() && s[i] != c; i++)
    {
        if(s[i] != "")
        {
            s[minIndex] = t;
            s.erase(minIndex, 1);
        }
    }
    return t;
}

MyProgrammingLab is saying that this is not the correct solution. Is there anything I need to add or fix in this sort function? Any help would be appreciated.

Recommended Answers

All 3 Replies

Just an exercise in pure logic thinking.
Why would erasing a character from a string would sort a string?

I'm not sure, but that is what I am required to use for that problem. So what do I need to fix for this function?

I've spotted a pattern to your questions. You write something that compiles, then when it turns out to be wrong, you come here and ask us to do your homework for you.

Perhaps you should be putting a bit more effort into thinking about the problems and, more importantly, testing your code.

Tell me, what exactly is the value of 'c' on line 6? Why do you even hafve minIndex, since you set it to zero and never ever change it? Did you basically copy some words from the question, and then just write random code with those words in?

Now find minIndex:

That's what the question tells you to do. You aren't doing that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.