void sort3(int*a, int* b, int* c) { // Manual bubble-sorting... sort2(a,b); sort2(b,c); sort2(a,b); }
void sort2(int *arr, int low, int high) { int pivot, i, j, temp; if(low < high) { pivot = low; // select a pivot element i = low; j = high; while(i < j) { // increment i till you get a number greater than the pivot element while(arr[i] <= arr[pivot] && i <= high) i++; // decrement j till you get a number less than the pivot element while(arr[j] > arr[pivot] && j >= low) j--; // if i < j swap the elements in locations i and j if(i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // when i >= j it means the j-th position is the correct position // of the pivot element, hence swap the pivot element with the // element in the j-th position temp = arr[j]; arr[j] = arr[pivot]; arr[pivot] = temp; // Repeat quicksort for the two sub-arrays, one to the left of j // and one to the right of j sort2(arr, low, j-1); sort2(arr, j+1, high); } }
void sort3(int *conds, int *out3, int *in3) { conds[0] = sort2(out3,in3); in3[1] = out3[1]; conds[1] = sort2(out3+1,in3+1); in3[0] = out3[0]; in3[1] = out3[1]; conds[2] = sort2(out3,in3); }
int main () { int u = 2; int v = 3; int w = 4; int x = 1; sort2(u, v); sort2(w, x); cout << "u : " << u << endl << "v : " << v << endl << "w : " << w << endl << "x : " << x << endl; }
int sort2(int *numbers,int left, int right) { int mid; int inv=0; if (right > left) { mid = (right + left) / 2; inv+=sort2(numbers,left, mid); inv+=sort2(numbers,mid+1, right); inv+=merge2(numbers,left, mid+1, right); } return inv; }
int main() { char a[1005]; int m,n,i,l,j; __int64 b; while(scanf("%s",a)!=EOF) { m=0; l=strlen(a); i=0; while(a[m]=='5') m++; for(;m<l;) { b=0; n=0; while(a[m]!='5'&&m<l) { b=b*10+(a[m]-'0'); m++; n=1; } if(n==1) f[i++]=b; m++; } if(i<=20) sort1(0,i-1); else sort2(0,i-1); for(j=0;j<i-1;j++) printf("%I64d ",f[j]); printf("%d\n",f[j]); } return 0; }
int main() { int length, index; printf("Enter length of array\n"); scanf("%d", &length); int *array, *array1, *array2; array = (int*)malloc(100*sizeof(int)); array1 = (int*)malloc(100*sizeof(int)); array2 = (int*)malloc(100*sizeof(int)); for (index = 0; index < length; index++) { scanf("%d", &array[index]); if ((array[index]<0) || (array[index]>1)) { printf("Invalid input-enter either o or 1"); return 0; } array1[index] = array[index]; array2[index] = array[index]; } sort1(array, length); for (index = 0; index < length; index++) printf("%d\t", array[index]); sort2(array1, length); for (index = 0; index < length; index++) printf("%d\t", array1[index]); sort3(array2, length); for (index = 0; index < length; index++) printf("%d\t", array2[index]); getch(); }
int main(int argc, const char * argv[]) { //快速 printf("Hello, World!!\n"); //int a[6] = {3,1,2,5,6,4} ; int a[SIZE] = {95, 45, 15, 78, 84, 51, 24, 12}; //sort2(a, 0, 5) ; sort2(a, 0, 7) ; int len = sizeof(a)/sizeof(int); printf("%2d\n",len) ; for(int i=0;i<len;i++) { printf("a[%d]=%d\n",i,a[i]); } //冒泡 // int number[SIZE] = {95, 45, 15, 78, 84, 51, 24, 12}; // int i; // bubble_sort(number, SIZE); // for (i = 0; i < SIZE; i++) // { // printf("%d\n", number[i]); // } // printf("\n"); return 0; }
int main(){ omp_set_num_threads(THREADS); srand(time(0)); init_array(); // print_array(); struct timeval t1, t2; double elapsedTime; gettimeofday(&t1, NULL); sort1(); gettimeofday(&t2, NULL); elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("case 1. data length: %d, threads: %d, time: %gms\n", N, THREADS, elapsedTime); init_array(); gettimeofday(&t1, NULL); sort2(); gettimeofday(&t2, NULL); elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("case 2. data length: %d, groups: %d, threads: %d, time: %gms\n", N, GROUPS, THREADS, elapsedTime); return 0; }
MatrixArrayType& FileReader::calculateNearestNeigbhor(int NUMOFANTS) { int n = m_strVector.size(); int i = 0; double *pHelpArray = new double[m_strVector.size() ]; double *pdistanceArray = new double[m_strVector.size() ]; *(pdistanceArray) = std::numeric_limits<double>::max(); static MatrixArrayType neigbhors(n , NUMOFANTS); for (int node = 0; node < n; node++) { for (i = 0; i < n; i++) { *(pdistanceArray+i)=(*m_theMatrix)[node][i]; *(pHelpArray+i)= i; } double max = std::numeric_limits<double>::max() - 1; *(pdistanceArray+node) = 100000000; // set to a large value .. sort2(pdistanceArray, pHelpArray, 0, n - 1); for (i = 0; i < NUMOFANTS; i++) { neigbhors[node][i] = *(pHelpArray+i); } } this->m_nearestneighborMatrix = &neigbhors; return *m_nearestneighborMatrix; }
void sort2(int x,int y) { __int64 key=f[x]; int i=x,j=y; if(i>j) return ; while(i!=j) { while(j>i&&f[j]>=key) j--; f[i]=f[j]; while(i<j&&f[i]<=key) i++; f[j]=f[i]; } f[j]=key; sort2(x,j-1); sort2(j+1,y); }
void Sort(int n) { char ch; cout<<endl<<endl; cout<<"1. Sort accoring to School Code"<<endl; cout<<"2. Sort accoring to School Name"<<endl; ch=getch(); if(ch=='1') sort1(n); else sort2(n); }
int main() { int t,i,j,h,*a,*b,*c,ans; scanf("%d",&t); for(i=0;i<t;i++) { scanf("%d %d %d",&n,&m,&k); a = (int *)malloc(sizeof(int)*k); b = (int *)malloc(sizeof(int)*k); c = (int *)malloc(sizeof(int)*k); for(j=0;j<k;j++) scanf("%d %d",&a[j],&b[j]); sort(a,b,0,k-1); for(j=0;j<k;j++) {c[j]=b[j];} ans = sort2(c,0,k-1); for(j=1;j<k;j++) { h = j-1; while(a[h]==a[j]) j++; if(j-h>=2) ans-=sort2(b,h,j-1); } printf("Test case %d: %d\n",i+1,ans); free(a); free(b); free(c); } return 0; }
void spear(float data1[], float data2[], unsigned long n, float *d, float *zd, float *probd, float *rs, float *probrs) { float betai(float a, float b, float x); void crank(unsigned long n, float w[], float *s); float erfcc(float x); void sort2(unsigned long n, float arr[], float brr[]); unsigned long j; float vard,t,sg,sf,fac,en3n,en,df,aved,*wksp1,*wksp2; wksp1=vector(1,n); wksp2=vector(1,n); for (j=1;j<=n;j++) { wksp1[j]=data1[j]; wksp2[j]=data2[j]; } sort2(n,wksp1,wksp2); crank(n,wksp1,&sf); sort2(n,wksp2,wksp1); crank(n,wksp2,&sg); *d=0.0; for (j=1;j<=n;j++) *d += SQR(wksp1[j]-wksp2[j]); en=n; en3n=en*en*en-en; aved=en3n/6.0-(sf+sg)/12.0; fac=(1.0-sf/en3n)*(1.0-sg/en3n); vard=((en-1.0)*en*en*SQR(en+1.0)/36.0)*fac; *zd=(*d-aved)/sqrt(vard); *probd=erfcc(fabs(*zd)/1.4142136); *rs=(1.0-(6.0/en3n)*(*d+(sf+sg)/12.0))/sqrt(fac); fac=(*rs+1.0)*(1.0-(*rs)); if (fac > 0.0) { t=(*rs)*sqrt((en-2.0)/fac); df=en-2.0; *probrs=betai(0.5*df,0.5,df/(df+t*t)); } else *probrs=0.0; free_vector(wksp2,1,n); free_vector(wksp1,1,n); }
void sort2(double v[], long int v2[], long int left, long int right) /* FUNCTION: recursive routine (quicksort) for sorting one array; second arrays does the same sequence of swaps INPUT: two arrays, two indices OUTPUT: none (SIDE)EFFECTS: elements at position i and j of the two arrays are swapped */ { long int k, last; if (left >= right) return; swap2(v, v2, left, (left + right)/2); last = left; for (k=left+1; k <= right; k++) if (v[k] < v[left]) swap2(v, v2, ++last, k); swap2(v, v2, left, last); sort2(v, v2, left, last); sort2(v, v2, last+1, right); }
void sort2(int *a, int left, int right) { if(left >= right)/*如果左边索引大于或者等于右边的索引就代表已经整理完成一个组了*/ { return ; } int i = left; int j = right; int key = a[left]; while(i < j) /*控制在当组内寻找一遍*/ { while(i < j && key <= a[j]) /*而寻找结束的条件就是,1,找到一个小于或者大于key的数(大于或小于取决于你想升 序还是降序)2,没有符合条件1的,并且i与j的大小没有反转*/ { j--;/*向前寻找*/ } a[i] = a[j]; /*找到一个这样的数后就把它赋给前面的被拿走的i的值(如果第一次循环且key是 a[left],那么就是给key)*/ while(i < j && key >= a[i]) /*这是i在当组内向前寻找,同上,不过注意与key的大小关系停止循环和上面相反, 因为排序思想是把数往两边扔,所以左右两边的数大小与key的关系相反*/ { i++; } a[j] = a[i]; } a[i] = key;/*当在当组内找完一遍以后就把中间数key回归*/ sort2(a, left, i - 1);/*最后用同样的方式对分出来的左边的小组进行同上的做法*/ sort2(a, i + 1, right);/*用同样的方式对分出来的右边的小组进行同上的做法*/ /*当然最后可能会出现很多分左右,直到每一组的i = j 为止*/ }
int main() { int* ra; int rb[5]; int sa[3]; int a,b,c,ind; int m[9]; int n[7]; int l[6]; srand (time(NULL)); for(int i=0;i<7;i++) s[i]=0; printf("Ну, мы создали три массива:\n"); rndArray(&m,9,14,20); rndArray(&n,7,14,20); rndArray(&l,6,14,20); printArray(&m,9);printArray(&n,7);printArray(&l,6); for(int i=0;i<7;i++) { if(s[i]==3) printf("Число %d содержится во всех массивах!\n",i+14); } printf("\n\n\n ===== Это была одиннадцатая СР, теперь тринадцатая. =====\n\n\n(Используем тот же массив)"); printf("Вот у нас есть массив:\n"); printArray(&m,9); printf("Мы взяли его элементы, стоящие на четных местах, и поменяли их порядок на обратный:\n"); revArray(&m,9); printArray(&m,9); printf("Теперь мы сохранили этот массив в файл, а потом загрузили другой:\n"); save(&m,9); load(&m,5); printArray(&m,5); printf("Давайте вставим в наш массив другой массив из трех чисел. Каких? \n"); printf("Число 1: "); scanf("%d",&a); printf("Число 2: "); scanf("%d",&b); printf("Число 3: "); scanf("%d",&c); sa[0]=a; sa[1]=b; sa[2]=c; printf("С какого индекса начать? "); scanf("%d",&ind); ra = insert(&m,5,&sa,3,ind); printf("\nВот что получилось: \n"); printArray(ra,8); rem(ra,8,ind,3); printf("А теперь мы убрали добавленные элементы: \n"); printArray(ra,5); printf("\n\n\n ===== Это была тринадцатая СР, теперь четырнадцатая. =====\n\n\n(Используем тот же массив)"); printArray(ra,5); for(int i=0;i<5;i++) rb[i]=ra[i]; // Игра "найди костыль" продолжается! sort(ra,5); printf("После сортировки A: \n"); printArray(ra,5); sort2(rb,5); printf("После сортировки B: \n"); printArray(ra,5); return 0; }
bool FlashText::getBounds(float& left, float& top, float& right, float& bottom, IFlashDisplayObject* targetCoordinateSystem){ if ( targetCoordinateSystem == 0 ){ left = 0; top = 0; right = width; bottom = height; sort2(left, right); sort2(top, bottom); }else{ float tx, ty; tx = 0; ty = 0; localToTarget(tx, ty, targetCoordinateSystem); left = right = tx; top = bottom = ty; tx = 0 + width; ty = 0; localToTarget(tx, ty, targetCoordinateSystem); expand1(left, right, tx); expand1(top, bottom, ty); tx = 0; ty = 0 + height; localToTarget(tx, ty, targetCoordinateSystem); expand1(left, right, tx); expand1(top, bottom, ty); tx = 0 + width; ty = 0 + height; localToTarget(tx, ty, targetCoordinateSystem); expand1(left, right, tx); expand1(top, bottom, ty); } return true; }
int QuickSort::sort2(Array &array, int left, int right) const { if(left >= right) { // do nothing if less than 1 elements return 0; } /// @note Bob Sedgewick method int m = right + 1; /// printf("sort(%d-%d)\n", left, right); for(int i= right; i >= left; i--) { if(array[i] >= array[left]) { array.Swap(--m, i); } } sort2(array, left, m - 1); sort2(array, m + 1,right); return 0; }
int main (int argc, char **argv) { int i, count = 1000000; double stime; int *unsorted, *sorted, num_threads; if (argc >= 2) count = strtoul (argv[1], NULL, 0); unsorted = malloc (count * sizeof (int)); sorted = malloc (count * sizeof (int)); if (unsorted == NULL || sorted == NULL) { puts ("allocation failure"); exit (1); } srand (0xdeadbeef); for (i = 0; i < count; i++) unsorted[i] = rand (); omp_set_nested (1); omp_set_dynamic (0); #pragma omp parallel #pragma omp single nowait num_threads = omp_get_num_threads (); printf ("Threads: %d\n", num_threads); memcpy (sorted, unsorted, count * sizeof (int)); stime = omp_get_wtime (); sort1 (sorted, count); verify ("sort1", stime, sorted, count); memcpy (sorted, unsorted, count * sizeof (int)); stime = omp_get_wtime (); sort2 (sorted, count); verify ("sort2", stime, sorted, count); #if _OPENMP >= 200805 memcpy (sorted, unsorted, count * sizeof (int)); stime = omp_get_wtime (); sort3 (sorted, count); verify ("sort3", stime, sorted, count); #endif return 0; }
int main(){ int r,i,originalVector[VECTORSIZE],sortedVector[VECTORSIZE],testVector[VECTORSIZE]; /*seed random number*/ srand(1234); clock_t start, diff; /*initialize random number*/ for (i=0;i<VECTORSIZE;i++)originalVector[i]=rand()%10000; /*copy vector to sorted vector*/ memmove(sortedVector,originalVector,sizeof(originalVector)); /*insertion sort*/ start=clock(); /*start timer*/ insertion_sort(sortedVector,VECTORSIZE); printf ("Insertion sort took %d ms\n",(clock()-start)*1000/CLOCKS_PER_SEC); /*sort1*/ /*copy vector to test vector*/ memmove(testVector,originalVector,sizeof(originalVector)); start=clock(); /*start timer*/ sort1(testVector,VECTORSIZE); printf ("sort1 took %d ms\n",(clock()-start)*1000/CLOCKS_PER_SEC); /*check that it is sorted*/ if(!compareVectors(sortedVector,testVector,VECTORSIZE)){ printf("Sort1 failed\n"); return 0; } /*sort2*/ /*copy vector to test vector*/ memmove(testVector,originalVector,sizeof(originalVector)); start=clock(); /*start timer*/ sort2(testVector,VECTORSIZE); printf ("sort2 took %d ms\n",(clock()-start)*1000/CLOCKS_PER_SEC); /*check that it is sorted*/ if(!compareVectors(sortedVector,testVector,VECTORSIZE)){ printf("Sort2 failed\n"); return 0 ; } return 1; }
int QuickSort::Sort(Array &array) const { int ret = 0; switch (m_type) { case AlgorithmType_0: ret = sort0(array, 0, array.Size() -1); break; case AlgorithmType_Lomuto: ret = sort1(array, 0, array.Size() -1); break; case AlgorithmType_Sedgewick: ret = sort2(array, 0, array.Size() -1); break; case AlgorithmType_3: break; default: break; } return 0; }
void main() { int a[100], b[100]; int n, i, sum = 0; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &a[i]); if (a[i]!=0 && a[i]!=1) { printf("Please Enter only 0's and 1's\n"); i--; } else { sum = sum + a[i]; } } sort1(a, n,b); for (i = 0; i < n; i++) { printf("%d", b[i]); } printf("\n"); sort2(a, n, b,sum); for (i = 0; i < n; i++) { printf("%d", b[i]); } printf("\n"); sort3(a, n); for (i = 0; i < n; i++) { printf("%d", a[i]); } printf("\n"); getch(); }
void sort3(int iFrom, int iTo) { // iTo=19; int d=iFrom+getPow(iTo-iFrom); //if(d<2)return; sort2(iFrom,d); if(d!=iTo) { // printf("-------------marl=%d\n",d-iFrom); int iDif=iTo-d; if(iDif==1) { } else if(iDif==2) { join(d,d+1,iTo); } else if(iDif==3) { join(d,d+1,d+2); join(d,d+2,iTo); } /* else if(iTo-d<16)//shis var buut 0 { sort4(d,iTo); } */ else { sort3(d,iTo); } join(iFrom,d,iTo); } }
int main(void) { int i,j; float *data,*order,*s,**rays; char dummy[MAXSTR],txt[MAXSTR],city[NDAT+1][17],mon[NMON+1][5]; FILE *fp; data=vector(1,NDAT); order=vector(1,NDAT); s=vector(1,NMON); rays=matrix(1,NDAT,1,NMON); if ((fp = fopen("table2.dat","r")) == NULL) nrerror("Data file table2.dat not found\n"); fgets(dummy,MAXSTR,fp); fgets(txt,MAXSTR,fp); fscanf(fp,"%*15c"); for (i=1;i<=NMON;i++) fscanf(fp," %s",mon[i]); fgets(dummy,MAXSTR,fp); fgets(dummy,MAXSTR,fp); for (i=1;i<=NDAT;i++) { fscanf(fp,"%[^0123456789]",city[i]); city[i][16]='\0'; for (j=1;j<=NMON;j++) fscanf(fp,"%f",&rays[i][j]); fgets(dummy,MAXSTR,fp); } fclose(fp); printf("%s\n%16s",txt," "); for (i=1;i<=12;i++) printf(" %s",mon[i]); printf("\n"); for (i=1;i<=NDAT;i++) { printf("%s",city[i]); for (j=1;j<=12;j++) printf("%4d",(int) (0.5+rays[i][j])); printf("\n"); } printf(" press return to continue ...\n"); getchar(); /* Replace solar flux in each column by rank order */ for (j=1;j<=12;j++) { for (i=1;i<=NDAT;i++) { data[i]=rays[i][j]; order[i]=i; } sort2(NDAT,data,order); crank(NDAT,data,&s[j]); for (i=1;i<=NDAT;i++) rays[(int) (0.5+order[i])][j]=data[i]; } printf("%16s"," "); for (i=1;i<=12;i++) printf(" %s",mon[i]); printf("\n"); for (i=1;i<=NDAT;i++) { printf("%s",city[i]); for (j=1;j<=12;j++) printf("%4d",(int) (0.5+rays[i][j])); printf("\n"); } free_matrix(rays,1,NDAT,1,NMON); free_vector(s,1,NMON); free_vector(order,1,NDAT); free_vector(data,1,NDAT); return 0; }
static void compare(int32_t *a, int32_t n) { int32_t *b; int32_t i; double runtime; b = (int32_t *) safe_malloc((n + 1) * sizeof(int32_t)); runtime = get_cpu_time(); for (i=0; i<5000; i++) { copy_array(b, a, n); insertion_sort(b, n); } runtime = get_cpu_time() - runtime; // printf("isort: %.3f s\n", runtime); itime += runtime; runtime = get_cpu_time(); for (i=0; i<5000; i++) { copy_array(b, a, n); sort(b, n); } runtime = get_cpu_time() - runtime; // printf("sort1: %.3f s\n", runtime); time1 += runtime; runtime = get_cpu_time(); for (i=0; i<5000; i++) { copy_array(b, a, n); sort2(b, n); } runtime = get_cpu_time() - runtime; // printf("sort2: %.3f s\n", runtime); time2 += runtime; runtime = get_cpu_time(); for (i=0; i<5000; i++) { copy_array(b, a, n); sort3(b, n); } runtime = get_cpu_time() - runtime; // printf("sort3: %.3f s\n", runtime); time3 += runtime; runtime = get_cpu_time(); for (i=0; i<5000; i++) { copy_array(b, a, n); sort4(b, n); } runtime = get_cpu_time() - runtime; // printf("sort4: %.3f s\n\n", runtime); time4 += runtime; runtime = get_cpu_time(); for (i=0; i<5000; i++) { copy_array(b, a, n); sort4var(b, n); } runtime = get_cpu_time() - runtime; // printf("sort4var: %.3f s\n\n", runtime); time4var += runtime; runtime = get_cpu_time(); for (i=0; i<5000; i++) { copy_array(b, a, n); sort4var2(b, n); } runtime = get_cpu_time() - runtime; // printf("sort4var2: %.3f s\n\n", runtime); time4var2 += runtime; safe_free(b); }
int main() { std::vector<int> a; sort2(a.begin(),[](int,int){return false;}); }
int write_nemesis(std::string &nemI_out_file, Machine_Description* machine, Problem_Description* problem, Mesh_Description<INT>* mesh, LB_Description<INT>* lb, Sphere_Info* sphere) { int exoid; char title[MAX_LINE_LENGTH+1], method1[MAX_LINE_LENGTH+1]; char method2[MAX_LINE_LENGTH+1]; int cpu_ws = sizeof(float); int io_ws = sizeof(float); printf("Outputting load balance to file %s\n", nemI_out_file.c_str()); /* Create the load balance file */ /* Attempt to create a netcdf4-format file; if it fails, then assume that the netcdf library does not support that mode and fall back to classic netcdf3 format. If that fails, issue an error and return failure. */ int mode3 = EX_CLOBBER; int mode4 = mode3|EX_NETCDF4|EX_NOCLASSIC|problem->int64db|problem->int64api; ex_opts(EX_DEFAULT); // Eliminate misleading error if the first ex_create fails, but the second succeeds. if((exoid=ex_create(nemI_out_file.c_str(), mode4, &cpu_ws, &io_ws)) < 0) { /* If int64api or int64db non-zero, then netcdf-4 format is required, so fail now... */ if (problem->int64db|problem->int64api) { Gen_Error(0, "fatal: failed to create Nemesis netcdf-4 file"); return 0; } if((exoid=ex_create(nemI_out_file.c_str(), mode3, &cpu_ws, &io_ws)) < 0) { Gen_Error(0, "fatal: failed to create Nemesis file"); return 0; } } ON_BLOCK_EXIT(ex_close, exoid); /* Set the error reporting value */ if (error_lev > 1) ex_opts(EX_VERBOSE | EX_DEBUG); else ex_opts(EX_VERBOSE); /* Enable compression (if netcdf-4) */ ex_set_option(exoid, EX_OPT_COMPRESSION_LEVEL, 1); ex_set_option(exoid, EX_OPT_COMPRESSION_SHUFFLE, 1); /* Create the title */ if(problem->type == NODAL) strcpy(method1, "nodal"); else strcpy(method1, "elemental"); sprintf(title, "nem_slice %s load balance file", method1); strcpy(method1, "method1: "); strcpy(method2, "method2: "); switch(lb->type) { case MULTIKL: strcat(method1, "Multilevel-KL decomposition"); strcat(method2, "With Kernighan-Lin refinement"); break; case SPECTRAL: strcat(method1, "Spectral decomposition"); break; case INERTIAL: strcat(method1, "Inertial decomposition"); break; case ZPINCH: strcat(method1, "ZPINCH decomposition"); break; case BRICK: strcat(method1, "BRICK decomposition"); break; case ZOLTAN_RCB: strcat(method1, "RCB decomposition"); break; case ZOLTAN_RIB: strcat(method1, "RIB decomposition"); break; case ZOLTAN_HSFC: strcat(method1, "HSFC decomposition"); break; case LINEAR: strcat(method1, "Linear decomposition"); break; case RANDOM: strcat(method1, "Random decomposition"); break; case SCATTERED: strcat(method1, "Scattered decomposition"); break; } if(lb->refine == KL_REFINE && lb->type != MULTIKL) strcat(method2, "with Kernighan-Lin refinement"); else if(lb->type != MULTIKL) strcat(method2, "no refinement"); switch(lb->num_sects) { case 1: strcat(method1, " via bisection"); break; case 2: strcat(method1, " via quadrasection"); break; case 3: strcat(method1, " via octasection"); break; } /* Do some sorting */ for(int proc=0; proc < machine->num_procs; proc++) { /* Sort node maps */ gds_qsort(TOPTR(lb->int_nodes[proc]), lb->int_nodes[proc].size()); if(problem->type == NODAL) { sort2(lb->ext_nodes[proc].size(), TOPTR(lb->ext_nodes[proc]), TOPTR(lb->ext_procs[proc])); } /* Sort element maps */ gds_qsort(TOPTR(lb->int_elems[proc]), lb->int_elems[proc].size()); } /* Output the info records */ char *info[3]; info[0] = title; info[1] = method1; info[2] = method2; if(ex_put_info(exoid, 3, info) < 0) Gen_Error(0, "warning: output of info records failed"); /* Generate a QA record for the utility */ time_t time_val = time(nullptr); char *ct_ptr = asctime(localtime(&time_val)); char tm_date[30]; strcpy(tm_date, ct_ptr); /* Break string with null characters */ tm_date[3] = '\0'; tm_date[7] = '\0'; tm_date[10] = '\0'; tm_date[19] = '\0'; char qa_date[15], qa_time[10], qa_name[MAX_STR_LENGTH]; char qa_vers[10]; sprintf(qa_date, "%s %s %s", &tm_date[8], &tm_date[4], &tm_date[20]); sprintf(qa_time, "%s", &tm_date[11]); strcpy(qa_name, UTIL_NAME); strcpy(qa_vers, ELB_VERSION); if(qa_date[strlen(qa_date)-1] == '\n') qa_date[strlen(qa_date)-1] = '\0'; char **lqa_record = (char **)array_alloc(1, 4, sizeof(char *)); for(int i2=0; i2 < 4; i2++) lqa_record[i2] = (char *)array_alloc(1, MAX_STR_LENGTH+1, sizeof(char)); strcpy(lqa_record[0], qa_name); strcpy(lqa_record[1], qa_vers); strcpy(lqa_record[2], qa_date); strcpy(lqa_record[3], qa_time); printf("QA Record:\n"); for(int i2=0; i2 < 4; i2++) { printf("\t%s\n", lqa_record[i2]); } if(ex_put_qa(exoid, 1, (char *(*)[4]) &lqa_record[0]) < 0) { Gen_Error(0, "fatal: unable to output QA records"); return 0; } /* free up memory */ for(int i2=0; i2 < 4; i2++) free(lqa_record[i2]); free(lqa_record); /* Output the the initial Nemesis global information */ if(ex_put_init_global(exoid, mesh->num_nodes, mesh->num_elems, mesh->num_el_blks, 0, 0) < 0) { Gen_Error(0, "fatal: failed to output initial Nemesis parameters"); return 0; } /* Set up dummy arrays for ouput */ std::vector<INT> num_nmap_cnts(machine->num_procs); std::vector<INT> num_emap_cnts(machine->num_procs); if(problem->type == NODAL) { /* need to check and make sure that there really are comm maps */ for(int cnt=0; cnt < machine->num_procs; cnt++) { if (!lb->bor_nodes[cnt].empty()) num_nmap_cnts[cnt] = 1; } } else { /* Elemental load balance */ if(((problem->num_vertices)-(sphere->num)) > 0) { /* need to check and make sure that there really are comm maps */ for(int cnt=0; cnt < machine->num_procs; cnt++) { if (!lb->bor_nodes[cnt].empty()) num_nmap_cnts[cnt] = 1; } for(int cnt=0; cnt < machine->num_procs; cnt++) { if (!lb->bor_elems[cnt].empty()) num_emap_cnts[cnt] = 1; } } } if(ex_put_init_info(exoid, machine->num_procs, machine->num_procs, (char*)"s") < 0) { Gen_Error(0, "fatal: unable to output init info"); return 0; } // Need to create 5 arrays with the sizes of lb->int_nodes[i].size()... { std::vector<INT> ins(machine->num_procs); std::vector<INT> bns(machine->num_procs); std::vector<INT> ens(machine->num_procs); std::vector<INT> ies(machine->num_procs); std::vector<INT> bes(machine->num_procs); for (int iproc = 0; iproc < machine->num_procs; iproc++) { ins[iproc] = lb->int_nodes[iproc].size(); bns[iproc] = lb->bor_nodes[iproc].size(); ens[iproc] = lb->ext_nodes[iproc].size(); ies[iproc] = lb->int_elems[iproc].size(); bes[iproc] = lb->bor_elems[iproc].size(); } if(ex_put_loadbal_param_cc(exoid, TOPTR(ins), TOPTR(bns), TOPTR(ens), TOPTR(ies), TOPTR(bes), TOPTR(num_nmap_cnts), TOPTR(num_emap_cnts)) < 0) { Gen_Error(0, "fatal: unable to output load-balance parameters"); return 0; } } if(problem->type == NODAL) /* Nodal load balance output */ { /* Set up for the concatenated communication map parameters */ std::vector<INT> node_proc_ptr(machine->num_procs+1); std::vector<INT> node_cmap_ids_cc(machine->num_procs); std::vector<INT> node_cmap_cnts_cc(machine->num_procs); node_proc_ptr[0] = 0; for(int proc=0; proc < machine->num_procs; proc++) { node_proc_ptr[proc+1] = node_proc_ptr[proc] + 1; node_cmap_cnts_cc[proc] = lb->ext_nodes[proc].size(); node_cmap_ids_cc[proc] = 1; } /* Output the communication map parameters */ if(ex_put_cmap_params_cc(exoid, TOPTR(node_cmap_ids_cc), TOPTR(node_cmap_cnts_cc), TOPTR(node_proc_ptr), nullptr, nullptr, nullptr) < 0) { Gen_Error(0, "fatal: unable to output communication map parameters"); return 0; } /* Output the node and element maps */ for(int proc=0; proc < machine->num_procs; proc++) { /* Output the nodal map */ if(ex_put_processor_node_maps(exoid, TOPTR(lb->int_nodes[proc]), TOPTR(lb->bor_nodes[proc]), TOPTR(lb->ext_nodes[proc]), proc) < 0) { Gen_Error(0, "fatal: failed to output node map"); return 0; } /* Output the elemental map */ if(ex_put_processor_elem_maps(exoid, TOPTR(lb->int_elems[proc]), nullptr, proc) < 0) { Gen_Error(0, "fatal: failed to output element map"); return 0; } /* * Reorder the nodal communication maps so that they are ordered * by processor and then by global ID. */ /* This is a 2-key sort */ qsort2(TOPTR(lb->ext_procs[proc]), TOPTR(lb->ext_nodes[proc]), lb->ext_nodes[proc].size()); /* Output the nodal communication map */ if(ex_put_node_cmap(exoid, 1, TOPTR(lb->ext_nodes[proc]), TOPTR(lb->ext_procs[proc]), proc) < 0) { Gen_Error(0, "fatal: failed to output nodal communication map"); return 0; } } /* End "for(proc=0; proc < machine->num_procs; proc++)" */ } else if(problem->type == ELEMENTAL) /* Elemental load balance output */ { std::vector<INT> node_proc_ptr(machine->num_procs+1); std::vector<INT> node_cmap_ids_cc(machine->num_procs); std::vector<INT> node_cmap_cnts_cc(machine->num_procs); node_proc_ptr[0] = 0; for(int proc=0; proc < machine->num_procs; proc++) { node_proc_ptr[proc+1] = node_proc_ptr[proc] + 1; node_cmap_cnts_cc[proc] = 0; for(size_t cnt=0; cnt < lb->bor_nodes[proc].size(); cnt++) node_cmap_cnts_cc[proc] += lb->born_procs[proc][cnt].size(); node_cmap_ids_cc[proc] = 1; } std::vector<INT> elem_proc_ptr(machine->num_procs+1); std::vector<INT> elem_cmap_ids_cc(machine->num_procs); std::vector<INT> elem_cmap_cnts_cc(machine->num_procs); elem_proc_ptr[0] = 0; for(int proc=0; proc < machine->num_procs; proc++) { elem_proc_ptr[proc+1] = elem_proc_ptr[proc] + 1; elem_cmap_cnts_cc[proc] = lb->e_cmap_elems[proc].size(); elem_cmap_ids_cc[proc] = 1; } /* Output the communication map parameters */ if(ex_put_cmap_params_cc(exoid, TOPTR(node_cmap_ids_cc), TOPTR(node_cmap_cnts_cc), TOPTR(node_proc_ptr), TOPTR(elem_cmap_ids_cc), TOPTR(elem_cmap_cnts_cc), TOPTR(elem_proc_ptr)) < 0) { Gen_Error(0, "fatal: unable to output communication map parameters"); return 0; } /* Output the node and element maps */ for(int proc=0; proc < machine->num_procs; proc++) { /* Output the nodal map */ if(ex_put_processor_node_maps(exoid, TOPTR(lb->int_nodes[proc]), TOPTR(lb->bor_nodes[proc]), nullptr, proc) < 0) { Gen_Error(0, "fatal: failed to output node map"); return 0; } /* Output the elemental map */ if(ex_put_processor_elem_maps(exoid, TOPTR(lb->int_elems[proc]), TOPTR(lb->bor_elems[proc]), proc) < 0) { Gen_Error(0, "fatal: failed to output element map"); return 0; } /* * Build a nodal communication map from the list of border nodes * and their associated processors and side IDs. */ size_t nsize = 0; for(size_t cnt=0; cnt < lb->bor_nodes[proc].size(); cnt++) nsize += lb->born_procs[proc][cnt].size(); if (nsize > 0) { std::vector<INT> n_cmap_nodes(nsize); std::vector<INT> n_cmap_procs(nsize); size_t cnt3 = 0; for(size_t cnt=0; cnt < lb->bor_nodes[proc].size(); cnt++) { for(size_t cnt2=0; cnt2 < lb->born_procs[proc][cnt].size(); cnt2++) { n_cmap_nodes[cnt3] = lb->bor_nodes[proc][cnt]; n_cmap_procs[cnt3++] = lb->born_procs[proc][cnt][cnt2]; } } /* * Reorder the nodal communication maps so that they are ordered * by processor and then by global ID. */ /* This is a 2-key sort */ qsort2(TOPTR(n_cmap_procs), TOPTR(n_cmap_nodes), cnt3); /* Output the nodal communication map */ if(ex_put_node_cmap(exoid, 1, TOPTR(n_cmap_nodes), TOPTR(n_cmap_procs), proc) < 0) { Gen_Error(0, "fatal: unable to output nodal communication map"); return 0; } } /* End "if (nsize > 0)" */ /* Output the elemental communication map */ if(!lb->e_cmap_elems[proc].empty()) { if(ex_put_elem_cmap(exoid, 1, TOPTR(lb->e_cmap_elems[proc]), TOPTR(lb->e_cmap_sides[proc]), TOPTR(lb->e_cmap_procs[proc]), proc) < 0) { Gen_Error(0, "fatal: unable to output elemental communication map"); return 0; } } } /* End "for(proc=0; proc < machine->num_procs; proc++)" */ } return 1; } /*------------------------End write_nemesis()------------------------------*/
long * mRMR_selection (DataTable * myData, long nfea, FeaSelectionMethod mymethod) { long *feaInd = 0; if (!myData || !myData->data || !myData->data2d) { fprintf (stderr, "Line %d: The input data is NULL.\n", __LINE__); exit (1); return feaInd; } if (nfea < 0) { fprintf (stderr, "Line %d: The input data nfea is negative.\n", __LINE__); exit (1); return feaInd; } long poolUseFeaLen = 500; if (poolUseFeaLen > myData->nvar - 1) // there is a target variable (the first one), that is why must remove one poolUseFeaLen = myData->nvar - 1; if (nfea > poolUseFeaLen) nfea = poolUseFeaLen; feaInd = new long[nfea]; if (!feaInd) { fprintf (stderr, "Line %d: Fail to allocate memory.\n", __LINE__); exit (1); return feaInd; } long i, j; //determine the pool float *mival = new float[myData->nvar]; float *poolInd = new float[myData->nvar]; char *poolIndMask = new char[myData->nvar]; if (!mival || !poolInd || !poolIndMask) { fprintf (stderr, "Line %d: Fail to allocate memory.\n", __LINE__); exit (1); return feaInd; } for (i = 0; i < myData->nvar; i++) //the mival[0] is the entropy of target classification variable { mival[i] = -calMutualInfo (myData, 0, i); //set as negative for sorting purpose poolInd[i] = i; poolIndMask[i] = 1; //initialized to be everything in pool would be considered // if (i < nfea) printf ("poolInd[%d]=%d\t%5.3f\n", i, int (poolInd[i]), mival[i]); } // printf ("\n{%d}\n", myData->nvar - 1); float *NR_mival = mival; //vector_phc(1,myData->nvar-1); float *NR_poolInd = poolInd; //vector_phc(1,myData->nvar-1); sort2 (myData->nvar - 1, NR_mival, NR_poolInd); // note that poolIndMask is not needed to be sorted, as everything in it is 1 up to this point mival[0] = -mival[0]; printf ("\nTarget classification variable (#%d column in the input data) has name=%s \tentropy score=%5.3f\n", 0 + 1, myData->variableName[0], mival[0]); printf ("\n*** MaxRel features ***\n"); printf ("Order \t Fea \t Name \t Score\n"); for (i = 1; i < myData->nvar - 1; i++) { mival[i] = -mival[i]; if (i <= nfea) printf ("%d \t %d \t %s \t %5.3f\n", i, int (poolInd[i]), myData->variableName[int (poolInd[i])], mival[i]); } //mRMR selection long poolFeaIndMin = 1; long poolFeaIndMax = poolFeaIndMin + poolUseFeaLen - 1; feaInd[0] = long (poolInd[1]); poolIndMask[feaInd[0]] = 0; //after selection, no longer consider this feature poolIndMask[0] = 0; // of course the first one, which corresponds to the classification variable, should not be considered. Just set the mask as 0 for safety. printf ("\n*** mRMR features *** \n"); printf ("Order \t Fea \t Name \t Score\n"); printf ("%d \t %d \t %s \t %5.3f\n", 0 + 1, feaInd[0], myData->variableName[feaInd[0]], mival[1]); long k; for (k = 1; k < nfea; k++) //the first one, feaInd[0] has been determined already { double relevanceVal, redundancyVal, tmpscore, selectscore; long selectind; int b_firstSelected = 0; for (i = poolFeaIndMin; i <= poolFeaIndMax; i++) { if (poolIndMask[long (poolInd[i])] == 0) continue; //skip this feature as it was selected already relevanceVal = calMutualInfo (myData, 0, long (poolInd[i])); //actually no necessary to re-compute it, this value can be retrieved from mival vector redundancyVal = 0; for (j = 0; j < k; j++) redundancyVal += calMutualInfo (myData, feaInd[j], long (poolInd[i])); redundancyVal /= k; switch (mymethod) { case MID: tmpscore = relevanceVal - redundancyVal; break; case MIQ: tmpscore = relevanceVal / (redundancyVal + 0.0001); break; default: fprintf (stderr, "Undefined selection method=%d. Use MID instead.\n", mymethod); tmpscore = relevanceVal - redundancyVal; } if (b_firstSelected == 0) { selectscore = tmpscore; selectind = long (poolInd[i]); b_firstSelected = 1; } else { if (tmpscore > selectscore) { //update the best feature found and the score selectscore = tmpscore; selectind = long (poolInd[i]); } } } feaInd[k] = selectind; poolIndMask[selectind] = 0; printf ("%d \t %d \t %s \t %5.3f\n", k + 1, feaInd[k], myData->variableName[feaInd[k]], selectscore); } //return if (mival) { delete[]mival; mival = 0; } if (poolInd) { delete[]poolInd; poolInd = 0; } if (poolIndMask) { delete[]poolIndMask; poolIndMask = 0; } return feaInd; }
int main(int argc, char ** argv) { size_t n = DB::parse<size_t>(argv[1]); size_t method = DB::parse<size_t>(argv[2]); std::vector<Key> data(n); // srand(time(0)); { Stopwatch watch; for (auto & elem : data) elem = rand(); watch.stop(); double elapsed = watch.elapsedSeconds(); std::cerr << "Filled in " << elapsed << " (" << n / elapsed << " elem/sec., " << n * sizeof(Key) / elapsed / 1048576 << " MB/sec.)" << std::endl; } if (n <= 100) { std::cerr << std::endl; for (const auto & elem : data) std::cerr << elem << ' '; std::cerr << std::endl; } { Stopwatch watch; if (method == 1) sort1(&data[0], n); if (method == 2) sort2(&data[0], n); if (method == 3) sort3(&data[0], n); watch.stop(); double elapsed = watch.elapsedSeconds(); std::cerr << "Sorted in " << elapsed << " (" << n / elapsed << " elem/sec., " << n * sizeof(Key) / elapsed / 1048576 << " MB/sec.)" << std::endl; } { Stopwatch watch; size_t i = 1; while (i < n) { if (!(data[i - 1] <= data[i])) break; ++i; } watch.stop(); double elapsed = watch.elapsedSeconds(); std::cerr << "Checked in " << elapsed << " (" << n / elapsed << " elem/sec., " << n * sizeof(Key) / elapsed / 1048576 << " MB/sec.)" << std::endl << "Result: " << (i == n ? "Ok." : "Fail!") << std::endl; } if (n <= 1000) { std::cerr << std::endl; std::cerr << data[0] << ' '; for (size_t i = 1; i < n; ++i) { if (!(data[i - 1] <= data[i])) std::cerr << "*** "; std::cerr << data[i] << ' '; } std::cerr << std::endl; } return 0; }