1 #include<math.h> 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<iostream> 5 using namespace std; 6 void kmeans(int n, float* xy, int k, float* cxy) 7 { 8 int i,j; 9 for(i=0;i<k;i++) 10 { 11 cxy[2*i]=xy[2*i]; 12 cxy[2*i+1]=xy[2*i+1]; 13 } 14 15 int* mindis=(int*)malloc(n*sizeof(int)); 16 int* premindis=(int*)malloc(n*sizeof(int)); 17 for(i=0;i<n;i++) 18 { 19 mindis[i]=-1; 20 } 21 int change=1; 22 23 while(change) 24 { 25 for(i=0;i<n;i++) 26 { 27 premindis[i]=mindis[i]; 28 } 29 for(i=0;i<n;i++) 30 { 31 float min=9999; 32 for(j=0;j<k;j++) 33 { 34 double s=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])); 35 if(s<min) 36 { 37 min=s; 38 mindis[i]=j; 39 } 40 } 41 } 42 43 /* 44 for(i=0;i<2;i++) 45 { 46 printf("%.3f ",cxy[2*i]); 47 printf("%.3f\n",cxy[2*i+1]); 48 } 49 */ 50 51 for(i=0;i<k;i++) 52 { 53 int num=0; 54 float s0=0.0; 55 float s1=0.0; 56 //cout<<i<<":"; 57 for(j=0;j<n;j++) 58 { 59 if(mindis[j]==i) 60 { 61 num++; 62 //cout<<j<<" "; 63 s0+=xy[2*j]; 64 s1+=xy[2*j+1]; 65 } 66 } 67 if(num) 68 { 69 cxy[2*i]=s0/num; 70 cxy[2*i+1]=s1/num; 71 } 72 //cout<<endl; 73 } 74 int flag=0; 75 for(i=0;i<n;i++) 76 { 77 if(mindis[i]!=premindis[i]) 78 { 79 flag=1; 80 break; 81 } 82 } 83 if(flag==0) 84 change=0; 85 } 86 87 88 } 89 int main() 90 { 91 float xy[12]={1.0, 1.0, 2.0, 1.0, 1.0, 2.0, 4.0, 5.0, 5.0, 4.0, 4.0, 4.0}; 92 float cxy[4]={0.0, 0.0, 0.0, 0.0}; 93 kmeans(6,xy,2,cxy); 94 int i; 95 for(i=0;i<2;i++) 96 { 97 printf("%.3f ",cxy[2*i]); 98 printf("%.3f\n",cxy[2*i+1]); 99 } 100 return 0; 101 }
时间: 2024-10-04 07:25:22