1#include <math.h>2#include <stdio.h>3#include <stdlib.h>4#include <iostream>5 using namespacestd;6 voidKmeans (intNfloat* XY,intKfloat*cxy)7 {8 inti,j;9 for(i=0; i<k;i++)Ten { Onecxy[2*i]=xy[2*i]; Acxy[2*i+1]=xy[2*i+1]; - } - the int* Mindis= (int*)malloc(nsizeof(int)); - int* Premindis= (int*)malloc(nsizeof(int)); - for(i=0; i<n;i++) - { +mindis[i]=-1; - } + intChange=1; A at while(change) - { - for(i=0; i<n;i++) - { -premindis[i]=Mindis[i]; - } in for(i=0; i<n;i++) - { to floatmin=9999; + for(j=0; j<k;j++) - { the DoubleS=sqrt ((xy[2*i]-cxy[2*J]) * (xy[2*i]-cxy[2*J]) + (xy[2*i+1]-cxy[2*j+1]) * (xy[2*i+1]-cxy[2*j+1])); * if(s<min) $ {Panax Notoginsengmin=s; -mindis[i]=J; the } + } A } the + /* - For (i=0;i<2;i++) $ { $ printf ("%.3f", Cxy[2*i]); - printf ("%.3f\n", cxy[2*i+1]); - } the */ - Wuyi for(i=0; i<k;i++) the { - intnum=0; Wu floats0=0.0; - floats1=0.0; About //cout<<i<< ":"; $ for(j=0; j<n;j++) - { - if(mindis[j]==i) - { Anum++; + //cout<<j<< ""; thes0+=xy[2*j]; -s1+=xy[2*j+1]; $ } the } the if(num) the { thecxy[2*i]=s0/num; -cxy[2*i+1]=s1/num; in } the //cout<<endl; the } About intflag=0; the for(i=0; i<n;i++) the { the if(mindis[i]!=Premindis[i]) + { -flag=1; the Break;Bayi } the } the if(flag==0) -Change=0; - } the the the } the intMain () - { the floatxy[ A]={1.0,1.0,2.0,1.0,1.0,2.0,4.0,5.0,5.0,4.0,4.0,4.0}; the floatcxy[4]={0.0,0.0,0.0,0.0}; theKmeans (6Xy2, cxy);94 inti; the for(i=0;i<2; i++) the { theprintf"%.3f", cxy[2*i]);98printf"%.3f\n", cxy[2*i+1]); About } - return 0;101}
View Code
K-Mean Clustering (c + +)