I have done bubble sort algorithm on a vector that is filled with randomly generated values. Bubble sort is actually done with the odd-even transposition method:
#include <iostream>
#include <algorithm>
#include <vector>
#include <random>
#include <thread>
#include <mutex>
void fill_with_random(std::vector<int> &vec)
{
constexpr int lower_bound = 1;
constexpr int upper_bound = 100;
std::random_device rnd_device;
std::mt19937 mersenne_engine(rnd_device());
std::uniform_int_distribution<int> distribution(lower_bound, upper_bound);
auto generator = std::bind(distribution, mersenne_engine);
std::generate(vec.begin(), vec.end(), generator);
}
bool is_odd(int number)
{
return number % 2 != 0;
}
int main(int argc, char *argv[])
{
constexpr size_t vector_size = 10;
std::mutex mutex;
std::vector<int> vec(vector_size);
fill_with_random(vec);
std::cout << "Normal vector: ";
for (auto item : vec)
{
std::cout << item << " ";
}
std::cout << std::endl;
for (size_t i = 0; i < vector_size; i++)
{
std::vector<std::thread> threads;
if (is_odd(i))
{
for (size_t j = 1; j < vector_size / 2 + vector_size % 2; j++)
{
size_t second = 2 * j;
size_t first = second - 1;
threads.emplace_back(
[&vec, first, second, &mutex]()
{
if (vec[first] > vec[second])
{
std::lock_guard<std::mutex> lock(mutex);
std::iter_swap(vec.begin() + first, vec.begin() + second);
}
}
);
}
}
else
{
for (size_t j = 0; j < vector_size / 2; j++)
{
size_t first = 2 * j;
size_t second = first + 1;
threads.emplace_back(
[&vec, first, second, &mutex]()
{
if (vec[first] > vec[second])
{
std::lock_guard<std::mutex> lock(mutex);
std::iter_swap(vec.begin() + first, vec.begin() + second);
}
}
);
}
}
for (auto& thread : threads)
{
thread.join();
}
}
std::cout << "Sorted vector: ";
for (auto item : vec)
{
std::cout << item << " ";
}
std::cout << std::endl;
return 0;
}
Next to a style review, please check functionality of the algorithm itself.
std::is_sorted()on your vector. You could write a loop that would check vectors up to certain size. \$\endgroup\$