Search code examples
c++sortinggarbage

Why garbage value showing up?


User enters a string like '3+2+1' or '1+3+2+1+3+1'. And I just have to sort the string. But after 4-5 test cases error shows up.

Input  - 2
Output - �

Input  - 2+1+2+2+2+3+1+3+1+2
Output - �+1+1+1+2+2+2+2+2+3
#include<iostream>
using namespace std;

int main()
{

    string s;
    cin>>s;

    for(int i=0;i<s.size();i+=2)
    {
        for(int j=0;j<(s.size()-i);j+=2)
        {
            if(s[j]>s[j+2])
            {
                swap(s[j],s[j+2]);
            }
        }
    }

    cout<<s;
    return 0;
}


Solution

  • As ggorlen said, garbage is showing up because you're accessing a value that's out of bounds. Try checking if your "j" index plus 2 is out of bounds before doing any swap.

    #include<iostream>
    using namespace std;
    
    int main()
    {
    
        string s;
        cin>>s;
    
        for(int i=0;i<s.size();i+=2)
        {
            for(int j=0;j<(s.size()-i);j+=2)
            {
                if(j+2 < s.size() && s[j]>s[j+2])
                {
                    swap(s[j],s[j+2]);
                }
            }
        }
    
        cout<<s;
        return 0;
    }
    

    Input 2+1+2+2+2+3+1+3+1+2

    Output 1+1+1+2+2+2+2+2+3+3