Skip to content

Commit 77b41e8

Browse files
authored
Add Sleep Sort in C++ (Fixes #3340) (#5179)
Also, update build command for C++ programs to support threading (Fixes Sleep Sort build issue)
1 parent d148d7e commit 77b41e8

File tree

2 files changed

+78
-2
lines changed

2 files changed

+78
-2
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <string>
4+
#include <thread>
5+
#include <mutex>
6+
#include <sstream>
7+
#include <chrono>
8+
9+
std::mutex mtx;
10+
std::vector<int> sorted_numbers;
11+
12+
void sortNumber(int number) {
13+
std::this_thread::sleep_for(std::chrono::seconds(number));
14+
std::lock_guard<std::mutex> lock(mtx);
15+
sorted_numbers.push_back(number);
16+
}
17+
18+
std::vector<int> parseInput(const std::string &input) {
19+
std::vector<int> numbers;
20+
std::stringstream ss(input);
21+
std::string token;
22+
23+
while (std::getline(ss, token, ',')) {
24+
try {
25+
int num = std::stoi(token);
26+
numbers.push_back(num);
27+
} catch (...) {
28+
throw std::invalid_argument("Invalid input");
29+
}
30+
}
31+
32+
return numbers;
33+
}
34+
35+
int main(int argc, char* argv[]) {
36+
if (argc != 2) {
37+
std::cerr << "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"\n";
38+
return 1;
39+
}
40+
41+
std::string input = argv[1];
42+
if (input.empty() || input[0] == ' ') {
43+
std::cerr << "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"\n";
44+
return 1;
45+
}
46+
47+
std::vector<int> numbers;
48+
try {
49+
numbers = parseInput(input);
50+
} catch (...) {
51+
std::cerr << "Usage: please provide a valid list of integers in the format \"1, 2, 3, 4, 5\"\n";
52+
return 1;
53+
}
54+
55+
if (numbers.size() < 2) {
56+
std::cerr << "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"\n";
57+
return 1;
58+
}
59+
60+
std::vector<std::thread> threads;
61+
for (int num : numbers) {
62+
threads.emplace_back(sortNumber, num);
63+
}
64+
65+
for (auto &t : threads) {
66+
t.join();
67+
}
68+
69+
for (size_t i = 0; i < sorted_numbers.size(); ++i) {
70+
std::cout << sorted_numbers[i];
71+
if (i < sorted_numbers.size() - 1) std::cout << ", ";
72+
}
73+
std::cout << std::endl;
74+
75+
return 0;
76+
}

archive/c/c-plus-plus/testinfo.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@ folder:
44

55
container:
66
image: "gcc"
7-
tag: "8.3"
8-
build: "g++ -o {{ source.name }} {{ source.name }}{{ source.extension }}"
7+
tag: "8.3"
8+
build: "g++ -std=c++17 -pthread -o {{ source.name }} {{ source.name }}{{ source.extension }}"
99
cmd: "./{{ source.name }}"

0 commit comments

Comments
 (0)