-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortlex.cpp
59 lines (54 loc) · 1.67 KB
/
shortlex.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
CMSC 141 - Exercise 1
Gisselle Derije and Leandrei Sagun
April 2, 2021
*/
#include<iostream>
#include<string>
#include<vector>
std::vector<std::string> L(std::vector<std::string> &words){
bool swapped = true; //boolean that determines if at least two strings are swapped
std::vector<std::string> w = words;
std::string u, v;
while(swapped){
swapped = false;
for(int i = 0; i < words.size() - 1; i++){
u = words[i]; //set u as the current string
v = words[i+1]; //set v as the next string
if(u.size() > v.size()){ //swaps the consecutive strings if the current string is longer than the next string
words[i] = v;
words[i+1] = u;
swapped = true;
break;
}
else if(u.size() == v.size()){
for(int j = 0; j < u.size(); j++){ //iterates the characters of both strings
if(u.at(j) > v.at(j)){ //swaps the consecutive strings if the current string has a larger character at the jth index
words[i] = v;
words[i+1] = u;
swapped = true;
break;
}
else if(u.at(j) < v.at(j)){ //ends the iteration if the current string has a smaller character at the jth index
break;
}
}
}
}
}
return words;
}
int main(){
std::vector<std::string> words = {"quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};
std::cout << "Original list of strings:" << std::endl;
for(std::string word : words){
std::cout << word << std::endl;
}
std::cout << std::endl;
words = L(words);
std::cout << "List of strings in shortlex order:" << std::endl;
for(std::string word : words){
std::cout << word << std::endl;
}
std::cout << std::endl;
}