I'm doing an exercise for fun (not homework), where given a sequence of strings sorted, with one word that appears too soon, we have to print the sequence sorted.
The point is that we have to do it with O(1) auxiliary space, so no vector
nor list
I tried the following:
#include <iostream>
#include <string>
using namespace std;
int main() {
string current, next, mal;
bool trobat = false;
cin >> current >> next;
while (next != "END") {
if (trobat) {
if (mal > current and mal < next) {
cout << current << endl;
cout << mal << endl;
trobat = false;
}
else {
cout << current << endl;
}
}
else if (current < next) {
cout << current << endl;
}
else {
trobat = true;
mal = current;
cout << next << endl;
}
current = next;
cin >> next;
}
if (trobat) {
cout << mal << endl;
}
else {
cout << current << endl;
}
}
Basically, I'm trying to have 3 strings: one with the current value to be treated, one with the next and one with the bad placed word, called mal
.
trobat
indicates if the word not sorted has been found but not printed yet.
If the word is correctly placed, we print it with the else if (current < next)
.
If not, I activate the flag trobat and print the next value, because the next has to be sorted.
Then, for the first if, if I found the value, I check if mal
is in the right position, otherwise I print the current and repeat the process.
I'm having troubles with the following tests:
INP1:
a
b
e
c
d
f
g
END
OUT1:
a
b
c
c
d
e
f
g
expected OUT1:
a
b
c
d
e
f
g
INP2:
f
aaaaaa
bbbbb
cccc
ddd
ee
END
OUT2:
aaaaaa
aaaaaa
bbbbb
cccc
ddd
f
expected OUT2:
aaaaaa
bbbbb
cccc
ddd
ee
f