How do I break this loop

This code orders all letters E to the left (esquerda in portuguese), and all letters D to the right (direita in portuguese). I want to stop the cout command when the line is ordered, but it keeps printing the same line.

imput: 8 DEEEDDDE
output:
DEEEDDDE
EDEEDDED
EEDEDEDD
EEEDEDDD
EEEEDDDD
EEEEDDDD
EEEEDDDD
EEEEDDDD

It should stop in the fifth line. Any help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>


using namespace std;

int main(){

    int n;
    cin >> n;

    char fila[n];
    for(int i=0;i<n;i++)
        cin >> fila[i];

    char aux;

    bool ordenado=false;

    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cout << fila[j];
        }
        cout << endl;

        for(int l=0;l<n;l++)
            if((fila[l]=='D' && fila[l+1]=='D') && (fila[l]=='E' && fila[l-1]=='E'))
                ordenado=true;

        if(ordenado)
            break;

        for(int k=0;k<n;k++){
            if(k!=n-1 && fila[k]=='D' && fila[k+1]=='E'){
                aux=fila[k+1];
                fila[k+1]=fila[k];
                fila[k]=aux;
                k++;
            }
        }
    }

    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <algorithm>

void bubble( std::string& str, int slno )
{
    for( std::size_t i = 0 ; i < str.size() ; ++i )
        for( std::size_t j = i+1 ; j < str.size() ; ++j )
            if( str[i] == 'D' && str[j] == 'E' ) // 'D' before an 'E'
            {
                std::swap( str[i], str[j] ) ; // swap them
                std::cout << slno << ". " << str << '\n' ; // print 
                bubble( str, slno+1 ) ; // continue bubbling
            }
}

int main()
{
    std::string str ;
    std::cin >> str ; // enter DEEEDDDE

    std::cout << "1. " << str << '\n' ;
    bubble( str, 2 ) ;
}

http://coliru.stacked-crooked.com/a/85065705bb968c4b
Thanks for the help, but I need the answer on my code, not another code using libraries that I didn't use before
Last edited on
Topic archived. No new replies allowed.