I wrote a k-means clustering algorithm and a color quantization algorithm. They work as expected in terms of results but I want to make them faster. In both implementations I need to solve a problem: there are two arrays of points in a 3D space, then for each point of the first array, you need to find the closest point from the second array. I do it like this:
size_t closest_cluster_index;
double x_dif, y_dif, z_dif;
double old_distance;
double new_distance;
for (auto point = points.begin(); point != points.end(); point++)
{
//FIX
//as suggested by juvian
//K = 1
if (point != points.begin())
{
auto cluster = &(clusters[closest_cluster_index]);
r_dif = cluster->r - point->r;
g_dif = cluster->g - point->g;
b_dif = cluster->b - point->b;
new_distance = r_dif * r_dif + g_dif * g_dif + b_dif * b_dif;
if (new_distance <= std::sqrt(old_distance) - ColorU8::differenceRGB(*(point - 1), *point))
{
old_distance = new_distance;
//do sth with closest_cluster_index;
continue;
}
}
//END OF FIX
old_distance = std::numeric_limits<double>::infinity();
for (auto cluster = clusters.begin(); cluster != clusters.end(); cluster++)
{
x_dif = cluster->x - point->x;
y_dif = cluster->y - point->y;
z_dif = cluster->z - point->z;
new_distance = x_dif * x_dif + y_dif * y_dif + z_dif * z_dif;
if (new_distance < old_distance)
{
old_distance = new_distance;
closest_cluster_index = cluster - clusters.begin();
}
}
//do sth with: closest_cluster_index
}
How can I improve it? (I don't want to make it multithreaded or computed by GPU)