Implementation of K-Means Algorithm in C++
The K-Means algorithm is one of the most widely used unsupervised machine learning algorithms. It partitions a dataset into K clusters such that each data point belongs to the cluster whose mean (centroid) it is closest to. Unlike KNN, K-Means does not use labelled data — it discovers natural groupings entirely on its own through iteration. In this post we walk through a well-commented C++ implementation of K-Means that clusters 10 integer values into 2 groups. We cover the algorithm, explain each line of code, trace through the iterative process, and analyse the output in detail. What is the K-Means Algorithm? K-Means works by alternating between two steps until the cluster centres stop changing: Assignment step: Assign each data point to the cluster whose mean it is closest to. Update step: Recalculate the mean of each cluster based on its current members. The algorithm converges when the means no longer change between iterations — meaning the clusters have stabilised. In this implementation: K = 2 (two clusters) Distance metric: absolute difference (1D Manhattan distance) Dataset: 10 integers entered by the user Initial means: provided by the user