int main() { FILE *f=fopen("heapsort.csv","w"); int i,n; for(n=10;n<=1000;n=n+10) { int a[n]; for(i=0;i<n;i++) { a[i]=rand()%10000; } heapsort(a,n); fprintf(f,"%d\n",counter); /*for(i=0;i<n;i++) { printf("%d ",a[i]); }*/ } //printf("%d\n",a[0]); return 0; }
void main() { char a[100][100],swap[100],tc,b[100]; int i,n,x; clock_t start,end; double exe_time; if(scanf("%d%c",&n,&tc)==2 && tc=='\n'&& n>0) { for(i=1;i<=n;i++) { scanf("%s",a[i]); strcpy(b,a[i]); if(validy(b)) continue; else { printf("\n Enter a valid string \n"); exit(1); } } start=clock(); heapsort(a,n); end=clock(); printf("\nThe sorted array is: \n"); for(i=1;i<=n;i++) { printf("%s\n",a[i]); } exe_time=(double)(end-start)/CLOCKS_PER_SEC; printf("The execution time is %lf \n",exe_time); } else { printf("\n Enter valid number \n"); exit(1); } }
// Custom introsort algorithm that combines quicksort, heapsort and insertion sort static void main_sort(T* vector, int left, int right, comparation(*expression)(T, T), int depth) { // Stop at the base case and calculate the length of the current vector if (left >= right) return; int len = right - left + 1; // If the maximum number of recursive calls has been reached, switch to heapsort if (depth == 0) heapsort(vector + left, len, expression); else { // Avoid the recursion and switch to insertion sort with small vectors if (len < MIN_QUICKSORT_SIZE) { insertion_sort(vector + left, len, expression); } else { // Classic quicksort step int part = partition(vector, left, right, expression); main_sort(vector, left, part - 1, expression, depth - 1); main_sort(vector, part + 1, right, expression, depth - 1); } } }
int main(void) { clock_t t0, t1; float t; const unsigned num_elems=1000; int *arr=genarr(num_elems); printf("Initial array:\n"); print_intarr(arr, num_elems); printf("\n"); t0 = clock(); heapsort(arr, num_elems); t1 = clock(); printf("\nFinal array:\n"); print_intarr(arr, num_elems); printf("\n\n"); t = (((float) t1) - ((float) t0))/((float) CLOCKS_PER_SEC); printf("The sort operation took %f seconds\n", t); //don't forget to free! free(arr); return 0; }
int main(int argc, char *argv[]) { #ifdef SMALL_PROBLEM_SIZE #define LENGTH 800000 #else #define LENGTH 8000000 #endif int N = ((argc == 2) ? atoi(argv[1]) : LENGTH); double *ary; int i; /* create an array of N random doubles */ ary = (double *)malloc((N+1) * sizeof(double)); for (i=1; i<=N; i++) { ary[i] = gen_random(1); } heapsort(N, ary); printf("%f\n", ary[N]); free(ary); return(0); }
void CSortManager::HeapSort(std::string inputfilepath, bool large) { long long int size = 0; if (large) size = ( INT_MAX / 4000 ); else size = 10000; try { CHeapSort heapsort(size); heapsort.FileToSort(inputfilepath); heapsort.Parse(); std::clock_t start; double duration; start = std::clock(); heapsort.Sort(); duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; std::string outfilepath = "sortedlist_heapsort.txt"; heapsort.WriteSortedListToFile(outfilepath); std::string sorttype = "Heap Sort"; if (largedataset) printTimingsLarge(sorttype, duration); else printTimingsSmall(sorttype, duration); } catch (std::exception ex) { CLogger::Log(__LINE__, __FILE__, ex.what()); } }
int main(int argc, char **argv) { heapsort(); return 0; }
int main(int argc, char **argv) { element list[27]; int i; element temp; for (i = 0; i < 27; i++) { list[i].key = i; } permute(list, 27); printf("before insert sort\n"); for (i = 0; i < 27; i++) { printf("%d " , list[i].key); } printf("\n"); insertion_sort(list, 27); printf("after insert sort\n"); for (i = 0; i < 27; i++) { printf("%d " , list[i].key); } printf("\n\n"); permute(list, 27); printf("before quik sort\n"); for (i = 0; i < 27; i++) { printf("%d " , list[i].key); } printf("\n"); quiksort(list, 0, 26); printf("after quik sort\n"); for (i = 0; i < 27; i++) { printf("%d " , list[i].key); } printf("\n\n"); permute(list, 27); printf("before merge sort\n"); for (i = 0; i < 27; i++) { printf("%d " , list[i].key); } printf("\n"); merge_sort(list, 27); printf("after merge sort\n"); for (i = 0; i < 27; i++) { printf("%d " , list[i].key); } printf("\n\n"); permute(list, 27); SWAP(list[0], list[26], temp); printf("before heap sort\n"); for (i = 0; i < 27; i++) { printf("%d " , list[i].key); } printf("\n"); heapsort(list, 26); printf("after heap sort\n"); for (i = 0; i < 27; i++) { printf("%d " , list[i].key); } printf("\n"); }
// This function creates a KD tree with the given // points, array, and length int KDTree::create(float *setpoints, int setnpoints, int setndim, bool setCopy, struct KDTreeNode *setNodeMem) { ndim = setndim; npoints = setnpoints; typedef int *intptr; // Copy the points from the original array, if necessary copyPoints = setCopy; if (copyPoints) { if(points) delete[] points; points = new float[ndim*npoints]; memcpy(points,setpoints,sizeof(float)*ndim*npoints); } // If we are not copying, just set the pointer else points = setpoints; // Allocate some arrays; if (workArr) delete[]workArr; workArr = new int[npoints]; if(!setNodeMem) { if(m_Root) delete[] m_Root; m_Root = new struct KDTreeNode[npoints*2+1]; nodeMemAlloc = true; } else { m_Root = setNodeMem; nodeMemAlloc = false; } nodeMemCnt = 0; // Alocate array used for indexing if(intArrMem) delete[] intArrMem; intArrMem = new int[(int)((float)(npoints+4)* ceil(log((double)npoints)/log(2.0)))]; intArrMemCnt = 0; // Create the "sortidx" array by // sorting the range tree points on each dimension int **sortidx = new intptr[ndim]; if(verbosity>1) logmsg("KDTree: Sorting points\n"); float imin[3]; float imax[3]; imin[0] = imin[1] = imin[2] = 999999.f; imax[0] = imax[1] = imax[2] = -999999.f; for (int i = 0; i < ndim; i++) { // Initialize the sortidx array for this // dimension sortidx[i] = new int[npoints]; // Initialize the "tmp" array for the sort int *tmp = new int[npoints]; for (int j = 0; j < npoints; j++) tmp[j] = j; // Sort the points on dimension i, putting // indexes in array "tmp" heapsort(i,tmp,npoints); // sortidx is actually the inverse of the // index sorts for (int j = 0; j < npoints; j++) { sortidx[i][tmp[j]] = j; imin[i] = min( points[ j*3 + i ], imin[ i ] ); imax[i] = max( points[ j*3 + i ], imax[ i ] ); } delete[] tmp; } if(verbosity > 1) logmsg("KDTree: Done sorting points\n"); // Create an initial list of points that references // all the points int *pidx = new int[npoints]; for (int i = 0; i < npoints; i++) pidx[i] = i; // Build a KD Tree AABB extents; Vec3 vmin( imin[0] , imin[1], imin[2] ); Vec3 vmax( imax[0] , imax[1], imax[2] ); OutputVector( vmin, "VMin"); OutputVector( vmax, "VMax"); extents.Set( vmin,vmax ); m_Root->bounds.Set( vmin, vmax ); //add objects to this node if( m_NodeCreationCallBack ) { (*m_NodeCreationCallBack)( m_Root ); } build_kdtree(sortidx, // array of sort values 0, // The current dimension pidx, npoints, extents); // The list of points // Delete the sort index for (int i = 0; i < ndim; i++) delete[]sortidx[i]; delete[] sortidx; // Delete the initial list of points delete[] pidx; // Delete the sort arrays delete[] intArrMem; // delete the work array if(workArr) { delete[] workArr; workArr = (int *)NULL; } if(verbosity > 1) logmsg("KDTree: Done creating tree\n"); return 0; } // end of create
void run_tests(int64_t *sizes, int sizes_cnt, int type) { int test, res; double usec1, usec2, diff; printf("-------\nRunning tests with %s:\n-------\n", test_names[type]); res = 0; diff = 0; printf("%-20s", "stdlib qsort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); qsort(dst, size, sizeof(int64_t), simple_cmp); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); #ifndef __linux__ res = 0; diff = 0; printf("%-20s", "stdlib heapsort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); heapsort(dst, size, sizeof(int64_t), simple_cmp); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); res = 0; diff = 0; printf("%-20s", "stdlib mergesort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); mergesort(dst, size, sizeof(int64_t), simple_cmp); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); #endif res = 0; diff = 0; printf("%-20s", "quick sort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); sorter_quick_sort(dst, size); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); if (MAXSIZE < 10000) { res = 0; diff = 0; printf("%-20s", "bubble sort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); sorter_bubble_sort(dst, size); usec2 = utime(); verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); res = 0; diff = 0; printf("%-20s", "binary insertion sort\n"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); sorter_binary_insertion_sort(dst, size); usec2 = utime(); verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); } res = 0; diff = 0; printf("%-20s", "merge sort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); sorter_merge_sort(dst, size); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); res = 0; diff = 0; printf("%-20s", "heap sort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); sorter_heap_sort(dst, size); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); res = 0; diff = 0; printf("%-20s", "shell sort time"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); sorter_shell_sort(dst, size); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); res = 0; diff = 0; printf("%-20s", "tim sort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); sorter_tim_sort(dst, size); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); res = 0; diff = 0; printf("%-20s", "in-place merge sort"); for (test = 0; test < sizes_cnt; test++) { int64_t size = sizes[test]; int64_t dst[size]; fill(dst, size, type); usec1 = utime(); sorter_merge_sort_in_place(dst, size); usec2 = utime(); res = verify(dst, size); if (!res) break; diff += usec2 - usec1; } printf(" - %s, %10.1f usec\n", res ? "ok" : "FAILED", diff); }
void CSRdouble::loadFromFileCOO(const char* file) { fstream fin(file, ios::in); cout << "opening file: " << file << " in mode: "; if (!fin.is_open()) { cout << "couldn't open file ... " << file << "\n"; exit(1); } cout << " ascii" << std::endl; fin >> nrows >> ncols >> nonzeros; cout << "nrows: " << nrows << std::endl; cout << "ncols: " << ncols << std::endl; cout << "nonzeros: " << nonzeros << std::endl; pRows = new int[nrows+1]; pCols = new int[nonzeros]; pData = new double[nonzeros]; int i, j, i0; double aij; int index; vector<vector<int> > vvcols(nrows+1); vector<vector<double> > vvdata(nrows+1); for (index = 0; index < nonzeros; index++) { fin >> i >> j >> aij; vvcols[i].push_back(j); vvdata[i].push_back(aij); } if (vvcols[0].empty()) i0 = 1; else i0 = 0; fin.close(); index = 0; pRows[0] = 0; for (i = i0; i < nrows+i0; i++) { int entries = vvcols[i].size(); heapsort(entries, &vvcols[i][0], &vvdata[i][0]); memcpy(&pData[index], &vvdata[i][0], entries*sizeof(double)); memcpy(&pCols[index], &vvcols[i][0], entries*sizeof(int)); index += entries; pRows[i+1-i0] = index; } for (i = 0; i < nrows+1; i++) { pRows[i] -= i0; } for (i = 0; i < nonzeros; i++) { pCols[i] -= i0; } }
void *heap(void *arg) { struct data *d = (struct data*) arg; heapsort((*d).a, (*d).size); }
void handler(struct hashtable *h_ex, struct hashtable *h_ex_in, struct hashtable *h_in, struct hashtable *h_in_in, keys *ex_keyhead, keys *in_keyhead, u_long in_bytes_count, u_int in_packets_count, u_long out_bytes_count, u_int out_packets_count) { struct hashtable *h_ex_old = h_ex, *h_ex_in_old = h_ex_in; struct hashtable *h_in_old = h_in, *h_in_in_old = h_in_in; keys *ex_keyhead_old = ex_keyhead, *in_keyhead_old = in_keyhead; keys *ex_ret, *ex_rethead, *in_ret, *in_rethead; value *v; xvalue vs[1025]; int sock; int i; struct sockaddr_in svraddr; // char sip[INET_ADDRSTRLEN], dip[INET_ADDRSTRLEN]; if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ syslog(LOG_ERR, "Socket: %s", strerror(errno)); exit(1); } svraddr.sin_family = AF_INET; svraddr.sin_port = htons(PORT); if(inet_pton(AF_INET, IP, &svraddr.sin_addr) < 0){ syslog(LOG_ERR, "inet_pton: %s", strerror(errno)); exit(1); } if (connect(sock, (const struct sockaddr *)&svraddr, sizeof(svraddr)) < 0){ syslog(LOG_ERR, "connect: %s", strerror(errno)); close(sock); return; } memset(&vs[0], 0, sizeof(xvalue)); vs[0].v.other = 0; vs[0].fbytes = out_bytes_count; vs[0].fpacket = out_packets_count; if (ex_keyhead_old->next){ if (!ex_keyhead_old->next->next){ v = hashtable_search(h_ex_old, ex_keyhead_old->next->key); vs[1].v = *v; if ((v = hashtable_search(h_ex_in_old, ex_keyhead_old->next->key)) == NULL){ vs[1].fbytes = 0; vs[1].fpacket = 0; }else{ vs[1].fbytes = v->bytes; vs[1].fpacket = v->packets; } write(sock, vs, sizeof(xvalue) * 2); /* if ((inet_ntop(AF_INET, &vs[1].v.sip, sip, INET_ADDRSTRLEN) == NULL) || (inet_ntop(AF_INET, &vs[1].v.dip, dip, INET_ADDRSTRLEN) == NULL)){ syslog(LOG_ERR, "inet_ntop: %s", strerror(errno)); return; } printf("Ex_in %s --> %s, bytes: %i, packets: %i\n", sip, dip, vs[1].v.bytes, vs[1].v.packets); */ }else{ if((ex_ret = heapsort(h_ex_old, ex_keyhead_old, 1)) == NULL) syslog(LOG_ERR, "heapSort error"); else{ ex_rethead = ex_ret; i = 1; for(ex_ret = ex_ret->next; ex_ret; ex_ret = ex_ret->next) { v = hashtable_search(h_ex_old, ex_ret->key); vs[i].v = *v; if ((v = hashtable_search(h_ex_in_old, ex_ret->key)) == NULL){ vs[i].fbytes = 0; vs[i].fpacket = 0; }else{ vs[i].fbytes = v->bytes; vs[i].fpacket = v->packets; } /* if ((inet_ntop(AF_INET, &vs[i].v.sip, sip, INET_ADDRSTRLEN) == NULL) || (inet_ntop(AF_INET, &vs[i].v.dip, dip, INET_ADDRSTRLEN) == NULL)){ syslog(LOG_ERR, "inet_ntop: %s", strerror(errno)); return; } printf("Ex_in %s --> %s, bytes: %i, packets: %i\n", sip, dip, vs[i].v.bytes, vs[i].v.packets); */ i++; } write(sock, vs, sizeof(xvalue) * i); for(; ex_rethead; free(ex_ret)) { ex_ret = ex_rethead; ex_rethead = ex_rethead->next; } } } }else write(sock, vs, sizeof(xvalue)); close(sock); if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ syslog(LOG_ERR, "Socket: %s", strerror(errno)); exit(1); } if (connect(sock, (const struct sockaddr *)&svraddr, sizeof(svraddr)) < 0){ syslog(LOG_ERR, "connect: %s", strerror(errno)); close(sock); return; } memset(&vs[0], 0, sizeof(xvalue)); vs[0].v.other = 1; vs[0].fbytes = in_bytes_count; vs[0].fpacket = in_packets_count; if (in_keyhead_old->next){ if (!in_keyhead_old->next->next){ v = hashtable_search(h_in_old, in_keyhead_old->next->key); vs[1].v = *v; if ((v = hashtable_search(h_in_in_old, in_keyhead_old->next->key)) == NULL){ vs[1].fbytes = 0; vs[1].fpacket = 0; }else{ vs[1].fbytes = v->bytes; vs[1].fpacket = v->packets; } write(sock, vs, sizeof(xvalue) * 2); /* if ((inet_ntop(AF_INET, &v->sip, sip, INET_ADDRSTRLEN) == NULL) || (inet_ntop(AF_INET, &v->dip, dip, INET_ADDRSTRLEN) == NULL)){ syslog(LOG_ERR, "inet_ntop: %s", strerror(errno)); return; } printf("In %s --> %s, bytes: %i, packets: %i\n", sip, dip, v->bytes, v->packets); */ }else{ if((in_ret = heapsort(h_in_old, in_keyhead_old, 0)) == NULL) syslog(LOG_ERR, "heapSort error"); else{ in_rethead = in_ret; i = 1; for(in_ret = in_ret->next; in_ret ; in_ret = in_ret->next) { v = hashtable_search(h_in_old, in_ret ->key); vs[i].v = *v; if ((v = hashtable_search(h_in_in_old, in_ret->key)) == NULL){ vs[i].fbytes = 0; vs[i].fpacket = 0; }else{ vs[i].fbytes = v->bytes; vs[i].fpacket = v->packets; } i++; /* if ((inet_ntop(AF_INET, &v->sip, sip, INET_ADDRSTRLEN) == NULL) || (inet_ntop(AF_INET, &v->dip, dip, INET_ADDRSTRLEN) == NULL)){ syslog(LOG_ERR, "inet_ntop: %s", strerror(errno)); return; } printf("In %s --> %s, bytes: %i, packets: %i\n", sip, dip, v->bytes, v->packets); */ } write(sock, vs, sizeof(xvalue) * i); for(; in_rethead; free(in_ret)) { in_ret = in_rethead; in_rethead = in_rethead->next; } } } }else write(sock, vs, sizeof(xvalue)); close(sock); }
void run_tests2(void) { int i; int64_t arr[SIZE]; int64_t dst[SIZE]; double start_time; double end_time; double total_time; printf("Running tests - 2\n"); srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); qsort(dst, SIZE, sizeof(int64_t), simple_cmp2); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("stdlib qsort time: %.2f us per iteration\n", total_time / RUNS); #ifndef __linux__ srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); heapsort(dst, SIZE, sizeof(int64_t), simple_cmp2); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("stdlib heapsort time: %.2f us per iteration\n", total_time / RUNS); srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); mergesort(dst, SIZE, sizeof(int64_t), simple_cmp2); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("stdlib mergesort time: %.2f us per iteration\n", total_time / RUNS); #endif srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); sorter2_quick_sort(dst, SIZE); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("quick sort time: %.2f us per iteration\n", total_time / RUNS); srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); sorter2_bubble_sort(dst, SIZE); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("bubble sort time: %.2f us per iteration\n", total_time / RUNS); srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); sorter2_merge_sort(dst, SIZE); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("merge sort time: %.2f us per iteration\n", total_time / RUNS); srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); sorter2_binary_insertion_sort(dst, SIZE); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("binary insertion sort time: %.2f us per iteration\n", total_time / RUNS); srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); sorter2_heap_sort(dst, SIZE); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("heap sort time: %.2f us per iteration\n", total_time / RUNS); srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); sorter2_shell_sort(dst, SIZE); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("shell sort time: %.2f us per iteration\n", total_time / RUNS); srand48(SEED); total_time = 0.0; for (i = 0; i < RUNS; i++) { fill(arr, SIZE); memcpy(dst, arr, sizeof(int64_t) * SIZE); start_time = utime(); sorter2_tim_sort(dst, SIZE); end_time = utime(); total_time += end_time - start_time; verify2(dst, SIZE); } printf("tim sort time: %.2f us per iteration\n", total_time / RUNS); }
static int MStep(Tsc *solucion){ Tsc estim_cp; int i,cnt,res; float error_ratio, error; float cosw, sinw, dtx, dty, tmp1, tmp2; static TAsoc cp_tmp[MAXLASERPOINTS+1]; // Filtering of the spurious data // Used the trimmed versions that orders the point by distance between associations if (params.filter<1){ // Add Null element in array position 0 (this is because heapsort requirement) for (i=0;i<cntAssociationsT;i++){ cp_tmp[i+1]=cp_associations[i]; } cp_tmp[0].dist=-1; // Sort array heapsort(cp_tmp, cntAssociationsT); // Filter out big distances cnt=((int)(cntAssociationsT*100*params.filter))/100; // Remove Null element for (i=0;i<cnt;i++){ cp_associationsTemp[i]=cp_tmp[i+1]; } } else{ // Just build the Temp array to minimize cnt=0; for (i=0; i<cntAssociationsT;i++){ if (cp_associations[i].dist<params.Br){ cp_associationsTemp[cnt]=cp_associations[i]; cnt++; } } } cntAssociationsTemp=cnt; #ifdef INTMATSM_DEB printf("All assoc: %d Filtered: %d Percentage: %f\n", cntAssociationsT, cntAssociationsTemp, cntAssociationsTemp*100.0/cntAssociationsT); #endif // --- /* Do de minimization Minimize Metric-based distance */ /* This function is optimized to speed up */ res=computeMatrixLMSOpt(cp_associationsTemp,cnt,&estim_cp); if (res==-1) return -1; #ifdef INTMATSM_DEB printf("estim_cp: <%f %f %f>\n",estim_cp.x, estim_cp.y,estim_cp.tita); printf("New impl: <%f %f %f>\n",estim_cp.x, estim_cp.y,estim_cp.tita); #endif cosw=(float)cos(estim_cp.tita); sinw=(float)sin(estim_cp.tita); dtx=estim_cp.x; dty=estim_cp.y; // ------ /* Compute the error of the associations */ error=0; for (i = 0; i<cnt;i++){ tmp1=cp_associationsTemp[i].nx * cosw - cp_associationsTemp[i].ny * sinw + dtx - cp_associationsTemp[i].rx;tmp1*=tmp1; tmp2=cp_associationsTemp[i].nx * sinw + cp_associationsTemp[i].ny * cosw + dty - cp_associationsTemp[i].ry;tmp2*=tmp2; error = error+ tmp1+tmp2; } error_ratio = error / error_k1; #ifdef INTMATSM_DEB printf("<err,errk1,errRatio>=<%f,%f,%f>\n estim=<%f,%f,%f>\n", error,error_k1,error_ratio, estim_cp.x,estim_cp.y, estim_cp.tita); #endif // ---- /* Check the exit criteria */ /* Error ratio */ if (fabs(1.0-error_ratio)<=params.error_th || (fabs(estim_cp.x)<params.errx_out && fabs(estim_cp.y)<params.erry_out && fabs(estim_cp.tita)<params.errt_out) ){ numConverged++; } else numConverged=0; //-- /* Build the solution */ composicion_sis(&estim_cp, &motion2, solucion); motion2=*solucion; error_k1=error; /* Number of iterations doing convergence (smooth criterion of convergence) */ if (numConverged>params.IterSmoothConv) return 1; else return 0; }
/* Função que ordena o Ranking da Metrica apontada pelo parâmetro, utilizando a chave de ordenação o campo pontuacao do TAD Ranking. O método de ordenação utilizado é HeapSort. */ void ordenaRankingMetrica(Metrica* metrica) { // Ordena o vetor de Ranking conforme o HeapSort heapsort(metrica->vetorRanking, metrica->quantidadeElementos); }
int main(void){ int *vetor1,*q, *vetorinverso; int cont, cont2, media, cont3, cont4; float tempo1, tempo2, tempo3, tempo4, iteracoes=10; int MAX=100000; clock_t Ti, Tf; float DeltaT; srand((unsigned)time(NULL)); printf("tamanho,quicksort_ordenacao,quicksort_jaordenado,quicksort_decrescente,mergesort_ordenacao,mergesort_jaordenado,mergesort_decrescente,heapsort_ordenacao,heapsort_jaordenado,heapsort_decrescente,shellsort_ordenacao,shellsort_jaordenado,shellsort_decrescente\n"); for(cont=0;cont<10;cont++){ vetor1=malloc(sizeof(int) * MAX); vetorinverso=malloc(sizeof(int) * MAX); tempo1=0; tempo2=0; tempo3=0; tempo4=0; for(cont2=0;cont2<10;cont2++){ for(cont3=0;cont3<MAX;cont3++){ vetor1[cont3]=rand() % MAX; } q=copiavetor(vetor1,MAX); Ti=clock(); quickSort(q,0,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; tempo1=tempo1+DeltaT; free(q); q=copiavetor(vetor1,MAX); Ti=clock(); merge_sort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; tempo2=tempo2+DeltaT; free(q); q=copiavetor(vetor1,MAX); Ti=clock(); heapsort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; tempo3=tempo3+DeltaT; free(q); q=copiavetor(vetor1,MAX); Ti=clock(); shellSort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; tempo4=tempo4+DeltaT; } cont4=0; for(cont3=MAX-1;cont3>=0;cont3--){ vetorinverso[cont4]=cont3; cont4++; } printf("%d,",MAX); //printf("quicksort;"); Ti=clock(); quickSort(q,0,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; printf("%f,",(tempo1/iteracoes)); printf("%f,",DeltaT); free(q); q=copiavetor(vetorinverso,MAX); Ti=clock(); quickSort(q,0,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; printf("%f,",DeltaT); //printf("mergesort\n"); Ti=clock(); merge_sort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; printf("%f,",tempo2/iteracoes); printf("%f,",DeltaT); free(q); q=copiavetor(vetorinverso,MAX); Ti=clock(); merge_sort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; printf("%f,",DeltaT); //printf("heapsort\n"); Ti=clock(); heapsort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; printf("%f,",tempo3/iteracoes); printf("%f,",DeltaT); free(q); q=copiavetor(vetorinverso,MAX); Ti=clock(); heapsort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; printf("%f,",DeltaT); //printf("shellsort\n"); Ti=clock(); shellSort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; printf("%f,",tempo4/iteracoes); printf("%f,",DeltaT); free(q); q=copiavetor(vetorinverso,MAX); Ti=clock(); shellSort(q,MAX-1); Tf=clock(); DeltaT=Tf-Ti; DeltaT=DeltaT/1000; printf("%f,",DeltaT); free(q); free(vetor1); free(vetorinverso); MAX=MAX+100000; printf("\n"); } return 0; }
int main(int argc, char *argv[]) { struct bildinfo geoinfo; /* alles zum Bildbearbeiten aus dem Header*/ struct bildattribut{ char name[128]; /* Struktur, um fuer jedes Bild die geo- */ int doy; /* zu verarbeiten */ double time; double gamma; double f; double dec; double EOT; double lon_sun; unsigned char headline[HDL]; /* Recordlaenge fuer "echte" Groesse */ short int **imagedata; /* matrix; msg data are assigned to imagedata */ byte **Bimagedata; /* Matrix, mfg data are assigned to Bimagedata */ }; struct bildattribut bildfolge[BILDANZ]; /* Zahl der Listenelemente: Monat = BILDANZ */ int rho_max=0; /* maximale Reflektivitaet bei Met-8 Bildern */ /* Cosinuskorrektur */ double GMT; /* Abscannzeitpunkt */ int quiet=0; /* Bildschirminformationen ? */ int accm; /* parameter for MFG GMT calculation */ int lin, col; /* Zaehlvariablen fuer Zeile und Spalte */ int n=0; /* Anzahl der verarbeiteten Bilder */ int decide; /* ausserhalb der Erde oder nicht */ double lat,lon; /* latitude and longitude in radians ! */ double corr; /* normalisierte Radianz */ double coszen; /* Cosinus des Zenitwinkels */ /* ---> SELFCALIBRATION: declarations */ /* RM May 2008: added file pointer frhomax,fstatrho */ FILE *out_image,*list,*f,*frhomax,*fstatrho; /* RM May 2008: fper and kend1 is needed for the caclulation of the percentile */ short int *fper = NULL; int kend1=0; /* RM May 2008: added averaged angles used for the caclculation of the scatter angle scata */ float msza=0; /* average of the solar zenith angle over time and space within the calibration region */ float mazi=0; /* average of the solar azimuth angle over time and space within the calibration region */ float msatazi=0; /* average of the sat azimuth angle .... */ float msatzen=0; /* average of the satellite zenith angle */ float scata=0; /* the mean scattering angle */ double satazi, satzen; /* geometry of MSG, satellite zenith and azimuth */ float r2d=180.0/3.1416; float esd; /* variable for the geometric correction of rho_max */ float dpos=0.0; /* dpos is the position of Meteosat relativ to lon=0, West is negative, East positive */ /* <--- SELFCALIBRATION declarations */ /* Dateinamen von Bildern */ char out_imagefile[160],groundpathname[128], cloudpathname[128],bild[128],bildpathname[128]; short int **out; /* Matrix fuer die Ausgabewerte */ short int reflectivity_vector[BILDANZ]; short int min, hour; char *cp; /* temporaere Werte */ char zeitname[4]; /* temporaerer ASCII-String der Zeit */ long zahl,anzahl; double cloudindex ; double db_hours_per_line; /* added in order to caclulate the timeoffset */ char *channel="MFGVIS"; /* added, currently hard wired, shoul be provided via heliosat call once the thermal irradiance is included */ short int MFG=1; /* added, currently hard wired, should be provided via heliosat call, once the routine is successfully tested for MFG and MSG !! */ int i,k,laenge; char quite='\0'; short int sig_ground, sig_shadow=0; /* width of distribution of cloudfree pixels and shaded pixels */ /* sig_shadow is zero, the shadow module will not be used, it is too slow and probably not needed if the fuzzy logic Heliosat version is used*/ short int(temp); float doffset=0; /* the dark/space offset of the instrument */ slope=(BYTE_MAX-BYTE_MIN)/(CLOUDI_MAX-CLOUDI_MIN); y_intercept=BYTE_MAX-CLOUDI_MAX*slope; /* DEFINE */ *out_imagefile = '\0'; for(i = 0;i <= BILDANZ;i++){*bildfolge[i].name = '\0';} /*** optionale Argumente von der command line lesen... ***/ if (argc<4) /* wenn nicht mindestens zwei opt.Parameter.. */ exit_print_usage(); /* .. dann schliesse das Programm */ for (i=1; i<argc; i++) /* fuer alle Argumente.. */ { cp=argv[i]; if (*cp!='-' && *cp!='/') /* pruefe ob Argument mit '-' oder '/' beginnt */ { fprintf(stderr,"bodenalbedo: no option specified (%s)\n",cp); exit_print_usage(); } cp++; if (*(cp+1)) /* pruefe ob an uebernaechster Stelle ein Blank */ { fprintf(stderr,"bodenalbedo: missing blank. Usage: -%c <arg>\n",*cp); exit(1); } *cp=(char) tolower((int) *cp); /* es wird nicht zwischen Klein- und * * Grossschreibung unterschieden */ if (*cp=='l') list=fopen(argv[++i],"rt"); else if (*cp=='b') strcpy(bildpathname,argv[++i]); else if (*cp=='c') strcpy(cloudpathname,argv[++i]); else if (*cp=='g') strcpy(groundpathname,argv[++i]); /* ---> SELFCALIBRATION dpos instead of sig_ground !!! */ else if (*cp=='s') dpos=atof(argv[++i]); /*dpos instead of sig_ground, see program header for details */ else if (*cp=='z') MFG=atoi(argv[++i]); /* MFG instead of sig_shadow MFG=1: MFG data expected MFG=0: MSG data */ else if (*cp=='q') quite='q'; else { fprintf(stderr,"bodenalbedo: unknown option: %s\n",cp); exit_print_usage(); } } if (dpos != 0.0) {printf("Meteosat position not at longitude=0 ! Please check -s in the heliosat call & set it to 0 if Met is at lon=0 \n");} if(MFG==1) {printf("assume MFG image data as input !! \n please check if you realy use MFG: -z has to be 0 for MSG \n");} else{ printf("assume MSG image data as input !! \n please check if you realy use MSG: -z has to be 1 for MFG \n"); } /* oeffnen aller Dateien, die in Liste stehen, Header auswerten, Matrizen zuweisen */ zahl=0; while(!feof(list) && anzahl < BILDANZ ) /* CaP - inserting the limit of BILDANZ to avoid coredumps*/ /* || anzahl < BILDANZ ) */ { anzahl=zahl; fscanf(list,"%s\r",bildfolge[anzahl].name); strcpy(bild,bildpathname); strcat(bild,"/"); strcat(bild,bildfolge[anzahl].name); if(!quite)printf("%d %s\n",anzahl,bild); read_xpif_header(HDL,bild,&bildfolge[anzahl].headline[0]); /* store header for output XPIF-images */ if(HDL==256) { bildfolge[anzahl].headline[11]=(unsigned char) 0; /* no additional headers wanted ! */ } if (MFG==1) { bildfolge[anzahl].Bimagedata=read_xpif_to_Bmatrix(HDL,bild,&geoinfo); bildfolge[anzahl].imagedata=smatrix(0,geoinfo.nrlines-1,0,geoinfo.nrcolumns-1); /* RM 17.07.09: dark offset and snanning time is different for MFG and MSG */ db_hours_per_line=(25./geoinfo.nrlines/60.); doffset=4.5*4; for (lin = 0;lin < geoinfo.nrlines;lin++) { /* change type and rotate the image, afterwards free bmatrix */ for(col = 0;col < geoinfo.nrcolumns;col++){ /* temp=(short int)bildfolge[anzahl].Bimagedata[geoinfo.nrlines-lin-1][geoinfo.nrcolumns-col-1]; */ /* correct if old openMTP converter is used */ bildfolge[anzahl].imagedata[lin][col]=4*(short int)bildfolge[anzahl].Bimagedata[geoinfo.nrlines-lin-1][geoinfo.nrcolumns-col-1]; /* correct if new openMTP to XPIF converter is used */ /* bildfolge[anzahl].imagedata[lin][col]=4*(short int)bildfolge[anzahl].Bimagedata[lin][col]; */ /* multiplication with factor 4 needed in order to have only one BYTE MAX definition */ /* (short int)bildfolge[anzahl].Bimagedata[lin][col]; */ /* (short int)bildfolge[anzahl].Bimagedata[geoinfo.nrlines-lin-1][geoinfo.nrcolumns-col-1]; */ /* printf("i,j,temp= %d %d %d",lin, col, temp); */ } } free_bmatrix(bildfolge[anzahl].Bimagedata,0,geoinfo.nrlines-1,0,geoinfo.nrcolumns-1); /* bildfolge[anzahl].Bimagedata=read_xpif_to_Bmatrix(HDL,bild,&geoinfo); */ } else{ bildfolge[anzahl].imagedata=read_xpif_to_matrix(HDL,bild,&geoinfo); db_hours_per_line=(12./geoinfo.nrlines/60.); doffset=51; } printf("Iam here 1 %d %d \n",geoinfo.nrlines, geoinfo.nrcolumns); bildfolge[anzahl].doy=geoinfo.doy; hour=geoinfo.aq_time /100; min=fmod(geoinfo.aq_time,100); bildfolge[anzahl].time=hour+min/60.0; bildfolge[anzahl].EOT=equation_of_time(bildfolge[anzahl].doy,&bildfolge[anzahl].gamma,&bildfolge[anzahl].f,&bildfolge[anzahl].dec); zahl++; } n=anzahl; printf ("n= %d \n",n); /* printf("doy is %04d %04d \n",geoinfo.doy, geoinfo.aq_time ); printf("nrs is %d %d %d %d \n",geoinfo.nrlines,geoinfo.nrcolbig,geoinfo.nrcolumns, geoinfo.nrlines ); printf("nrs is %d %d %d %d \n",geoinfo.line_off,geoinfo.col_off,geoinfo.nav_lres, geoinfo.nav_cres ); */ /* orig out=smatrix(0,geoinfo.nrlines-1,0,geoinfo.nrcolbig-1); RM 24.02->*/ out=smatrix(0,geoinfo.nrlines-1,0,geoinfo.nrcolumns-1); /*** Normalize images ---------------------------------------- ***/ /* allocate memory for fper 42610*/ /* fper = malloc(45000 * (n+1) * sizeof(short int)); if(fper == NULL) { fprintf(stderr, "not enough memory for array fper, needed for automatic calibration \n"); exit; } */ /* CaP - allocating only 2 bytes for now. Using realloc later in the loop below (line 719). The former memory allocation (previous line) causes severe memory errors and program crashes */ /* --> SELFCALIBRATION: initial allocation of field needed for the percentiles */ fper = malloc(sizeof(short int)); /* <-- */ printf("Iam here 2 \n"); accm=0; for (lin = 0;lin < geoinfo.nrlines;lin++) /* fuer alle Zeilen */ { /* 12.10.09 included new lines for the calculation of GMT. Now MFG and MSg can be processed */ /* old, orig for MSG GMT=bildfolge[anzahl].time+timeoffset(geoinfo.nav_lres,geoinfo.line_off,lin,15); */ /* GMT : Abscannzeitpunkt dieser Zeile bestimmen */ /* 17.07.09 fixed GMT bug, accm needed to consider that two subsequent lines are scanned in || */ accm=accm+abs((lin-1)%2); GMT=bildfolge[anzahl].time+(double)lin*db_hours_per_line; /* printf("now here vv \n");*/ if ((strcmp(channel,"MFGVIS")==0) && MFG==1) { /* CaP 29.04.2009 - in the vis imagery adjacent lines are scanned in couples */ GMT=bildfolge[anzahl].time+(double)(accm-1)*db_hours_per_line; /* printf("GMT,accm= %f %d \n",GMT ,accm); */ } /* orig GMT=bildfolge[anzahl].time+timeoffset(geoinfo.nav_lres,geoinfo.line_off,lin,15); */ /* GMT=bildfolge[anzahl].time+timeoffset(geoinfo.nav_lres,geoinfo.line_off,lin,15); */ for (k = 0 ;k <= n;k++) /* fuer alle Bilder */ { /* fuer Abscannzeit dieser Zeile und jeden Tag den Sonnenstand bestimmen */ bildfolge[k].lon_sun=(12.0-GMT-(bildfolge[k].EOT/60.0))*15*(PI/180.0); } /* printf("ere re re %d \n",k); */ for(col = 0;col < geoinfo.nrcolumns;col++) /* fuer alle Spalten */ { if(MFG==1){ decide=geoloc(lin,col,geoinfo.nrlines,&lat,&lon); } else{ decide=geomsg(geoinfo.nav_cres,geoinfo.nav_lres,geoinfo.col_off,geoinfo.line_off,lin,col,&lat,&lon); } /* if (decide == 0){ printf("the geoloc i,j,lat,lon %d %d %f %f \n", lin, col,lat*180/pi,lon*180/pi); } */ /* orig decide=geomsg(geoinfo.nav_cres,geoinfo.nav_lres,geoinfo.col_off,geoinfo.line_off,lin,col,&lat,&lon); */ /* ---> SELFCALIBRATION: calculation of additional angles */ /* RM Jul 2008: added equations for the calculation of satellite zenith and azimuth !! it is assumed that the satellite is at lat=lon=0 h=42164.0 height of geostationary Satellite */ satazi = atan(sin(lon-dpos/r2d)/tan(lat)); /* rm 072008 modified formular, covers all positions of Meteosat now */ /* old satzen = fabs(atan(sin(lat) * h/(cos(lat) * h - R_E))); */ satzen=90/r2d-atan((cos(dpos/r2d-lon)*cos(lat)-0.1512)/sqrt(1-pow(cos(dpos/r2d-lon),2)*pow(cos(lat),2))); /* <--- SELFCALIBRATION: calculation of additional angles */ if (decide==0) { for(k = 0 ;k <= n;k++) /* fuer alle Bilder */ { corr=0; coszen=cos_zenit(lat,lon,bildfolge[k].dec,bildfolge[k].lon_sun); if(coszen>0.02) corr = (int)((bildfolge[k].imagedata[lin][col]-doffset)/coszen); /* orig 51 instead of doffset */ corr = mini(corr,BYTE_MAX); corr = maxi(corr,BYTE_MIN); bildfolge[k].imagedata[lin][col] = corr; /* RM 20.11.07: automatic calculation of rho_max starts, sort vector content according to the value, in ascending order using heapsort, Numerical Recipies in C the 95 percentil * 1.1 is than the desired rhomax value */ /* ---> SELFCALIBRATION: Calculate the percentile and additional angles needed for the calculation of the scatter angle */ if(lat > -0.92 && lat < -0.8 && lon < (-0.01 + dpos/r2d) && lon > (-0.262+dpos/r2d)) /* -0.436*/ /* RM 072008: added +dpos in order to shift the reference region for Meteosat-East dpos=position of Meteosat relative to lon=0 in degree, west is negative */ { fper[kend1]=(short int)bildfolge[k].imagedata[lin][col]; /* assign values within region to fper */ kend1=kend1+1; /* calculate the mean angles as basis for the caclulation of the scatter angle, needed for the geometric correction of rhomax */ fper = realloc(fper,(kend1+1)*sizeof(short int)); msza=((kend1-1)*msza+acos(coszen))/kend1; mazi=((kend1-1)*mazi+azimuth(lat,lon,bildfolge[k].dec,acos(coszen),bildfolge[k].lon_sun))/kend1; msatazi=((kend1-1)*msatazi+satazi)/kend1; msatzen=((kend1-1)*msatzen+satzen)/kend1; } /* <--- end of SELFCALIBRATION: Calculate the percentile and additional angles needed for the calculation of the scatter angle */ } } if (decide==1){ out[lin][col] = (int) 0; for(k=1;k<=n;k++){ /* if(geoinfo.nrlines<200){doffset=doffset+ bildfolge[15].imagedata[lin][col];} */ bildfolge[k].imagedata[lin][col] = 0; } } } } printf("doffset= %f \n", doffset); printf("now I am here \n"); /* ---> SELFCALIBRATION: sorting the fper field and assignment of the percentiles */ heapsort(kend1, fper); /* order the counts */ int p1=(int)(0.1*(kend1+1)); int p3=(int)(0.3*(kend1+1)); int p5=(int)(0.5*(kend1+1)); int p7=(int)(0.7*(kend1+1)); int p8=(int)(0.8*(kend1+1)); int p9=(int)(0.9*(kend1+1)); int pm=(int)(0.95*(kend1+1)); /* <--- SELFCALIBRATION: sorting the fper field and assignment of the percentiles */ /* ---> SELFCALIBRATION: empirical correction of anisotropy for rho_max */ /* RM 28.05.08 empirical correction for scatter angle effect, so far formula only proven for 3 - 33 degree, RM 30.07.08 implemented new formula, correction works from 3-70 degree (scata), but probably only for the reference regions and not everywhere, above scattering angle of 32 the uncertainty of the geometric corrections is significnat higher */ scata=scatt_angle(msza, mazi, msatzen, msatazi); /* added new correction for rho_max, seems that the dominant effect comes from the sza dependent change of the cloud albedo, the clouds seems to reflect pretty well isotropic for a given SZA and rel AZA lower than 60 degree the correction formula results from a linear fit (gnuplot) applied to a 2.5 year time series for all slots with SZA>60 */ if (msza*r2d > 80.0 && msza*r2d <0.0) esd=1.0; /* gcor =1 for SZA>80 and <0*/ else {esd=1+0.0017*(45.0-msza*r2d); } /* <--- SELFCALIBRATION: empirical correction of anisotropic cloud reflection for rho_max */ /* ---> SELFCALIBRATION: Open and write the output files for information related to the self calibration approach */ fstatrho=fopen("rhostat.out","a") ; fprintf(fstatrho, "# kend1= %d doy= %d hour= %d min = %d \n",kend1,geoinfo.doy, hour,min); fprintf(fstatrho, " gcor= %f msza= %f mazi= %f satazi= %f satzen= %f scattangle= %f rhomax %f pm= %d \n", esd, msza*r2d, (mazi)*r2d, msatazi*r2d, msatzen*r2d, scata*r2d, fper[pm]*esd*1.1, fper[pm]); fprintf(fstatrho, "# ESD= %f rho(10,30,50,70,80,90,95)= %d %d %d %d %d %d %d rhomax %f \n",esd,fper[p1],fper[p3],fper[p5],fper[p7], fper[p8],fper[p9],fper[pm], fper[pm]*esd*1.1); if (hour==13 && min==0) { frhomax=fopen("rhomax.out","w"); /* RM 072008 changed r+ to w, r+ does not work properly on my machine */ rho_max=fper[pm]*esd*1.1; fprintf(frhomax, "%d \n", rho_max); fprintf(fstatrho,"## The noon rho_may is %d \n",rho_max ); fclose(frhomax); } else { /* if((frhomax=fopen("rhomax.out","r")) == NULL) */ if(file_exists("rhomax.out")) { frhomax=fopen("rhomax.out","r"); fscanf(frhomax, "%d", &rho_max); fprintf(fstatrho,"# Use noon rhomax from rhomax.out %d \n",rho_max ); printf("Use noon rhomax from rhomax,out %d \n",rho_max ); fclose(frhomax); } else { fprintf(fstatrho,"# WARNING Cannot open rhomax file, hence instead of the noon rhomax that of the actual slot is used,which might lead to higher uncertainty.\n"); rho_max=(int)fper[pm]*esd*1.1; fprintf(fstatrho,"# Use rhomax of actual slot %d \n",rho_max ); /*fclose(frhomax);*/ } } sig_ground=(short int)(0.035 * rho_max); fprintf(fstatrho,"# sig_ground =%d \n \n",sig_ground ); fclose(fstatrho); free(fper); /* <--- SELFCALIBRATION: Open and write the output files for information related to the self calibration approach */ printf("Finished normalizing images and automatic calibration \n"); /* * Grundalbedo and Cloud Index ---------------------------------------- */ for (lin = 0;lin < geoinfo.nrlines;lin++) /* fuer alle Pixel (Zeilen ... */ { for(col = 0; col < geoinfo.nrcolumns; col++) /* ... und Spalten) */ { for(k = 0; k<=n; k++) { /* copy all values to a vector, from these values ground albedo will de determined reflectivity_vector contains all reflectivity values for one location */ reflectivity_vector[k]=bildfolge[k].imagedata[lin][col]/bildfolge[k].f; /* /f correct for earth sun-distance **/ } /* calculation of ground albedo: out[lin][col]contains ground albedo reflectivity_vector contains cloud index values */ out[lin][col]=groundreflectivity_and_cloudindex(&reflectivity_vector[0], n, sig_ground, sig_shadow, rho_max); for(k = 0; k<=n; k++) { /* copy all cloud index values from vector back to matrix */ bildfolge[k].imagedata[lin][col]=reflectivity_vector[k]; } } } /*********************************************************************** * Ausgeben aller Bilder und Freisetzung des Speicherplatzes... ***********************************************************************/ /* Bodenalbedonamen zusammensetzen */ /* RM changed the naming of the reflectance files, mothly means for every slot are calculated and has to be saved, with the old naming they are overriden */ strcpy(out_imagefile,groundpathname); strcat(out_imagefile,"/"); sprintf(zeitname,"%04d",geoinfo.aq_time); strncat(out_imagefile,bildfolge[1].name,6); /* added string for year and month */ /*strncat(out_imagefile,zeitname,4);*/ strcat(out_imagefile,zeitname); /* printf("out_imagefile = %s bildfolge.name= %s\n",out_imagefile, bildfolge[1].name); */ if(HDL==256)strcat(out_imagefile,"hhmm.REF"); if(HDL==260)strcat(out_imagefile,"hhmm.REF.X260"); /* Grundalbedo speichern */ printf("nrbytes= %d",geoinfo.nrbytes) ; if (!(out_image=fopen(out_imagefile,"wb"))) exit_no_write(out_imagefile); if (MFG==1) {geoinfo.nrbytes=geoinfo.nrbytes*2;} /* dangerous, only for testing */ fwrite(&bildfolge[1].headline[0],HDL,1,out_image); /* orig fwrite(&out[0][0],geoinfo.nrcolbig*geoinfo.nrlines*(long)geoinfo.nrbytes,1,out_image); fclose(out_image); free_smatrix(out,0,geoinfo.nrlines-1,0,geoinfo.nrcolbig-1); */ fwrite(&out[0][0],geoinfo.nrcolumns*geoinfo.nrlines*(long)geoinfo.nrbytes,1,out_image); fclose(out_image); free_smatrix(out,0,geoinfo.nrlines-1,0,geoinfo.nrcolumns-1); for(k=0;k<=n;k++) { strcpy(out_imagefile,cloudpathname); strcat(out_imagefile,"/"); strncat(out_imagefile,bildfolge[k].name,strlen(bildfolge[k].name)-4); if(HDL==256)strcat(out_imagefile,"CI.XPIF"); if(HDL==260)strcat(out_imagefile,"CI.X260"); if (!(out_image=fopen(out_imagefile,"wb"))) exit_no_write(out_imagefile); fwrite(&bildfolge[k].headline[0],HDL,1,out_image); /* orig fwrite(&bildfolge[k].imagedata[0][0],geoinfo.nrcolbig*geoinfo.nrlines*(long)geoinfo.nrbytes,1,out_image); */ /* memcpy(void *dest, const void *src, size_t n);*/ bildfolge[k].Bimagedata=bmatrix(0,geoinfo.nrlines-1,0,geoinfo.nrcolumns-1); for (lin = 0;lin < geoinfo.nrlines;lin++) { for(col = 0;col < geoinfo.nrcolumns;col++){ bildfolge[k].Bimagedata[lin][col]=(byte)(bildfolge[k].imagedata[lin][col]/4); } } fwrite(&bildfolge[k].Bimagedata[0][0],geoinfo.nrcolumns*geoinfo.nrlines,1,out_image); free_bmatrix(bildfolge[k].Bimagedata,0,geoinfo.nrlines-1,0,geoinfo.nrcolumns-1); fclose(out_image); free_smatrix(bildfolge[k].imagedata,0,geoinfo.nrlines-1,0,geoinfo.nrcolumns-1); /* orig geoinfo.nrcolbig-1 */ } return(0); }
/* *worker thread to sort a portion of the set of numbers * */ void * thr_fn(void *arg) { long idx = (long)arg; heapsort(&nums[idx],TNUM,sizeof(long),complong); pthread_barrier_wait(&b); return ((void*)0); }
int DArray_heapsort(DArray *array, DArray_compare cmp) { return heapsort(array->contents, DArray_count(array), sizeof(void *), cmp); }
void heap_sort (int *v, int n) { heapsort (n, v - 1); }
void lib_hsort(int *values, int n) { heapsort(values, n, sizeof(values[0]), mycompare); }
std::vector<Coord> AStar( std::vector< std::vector< int > > grid, Point start, Point end ) { //The current 'focal' point. Point *cur; //The open and closed lists. std::vector< Point* > closed; std::vector< Point* > open; //Start by adding the starting position to the list. open.push_back( &start ); //Just so it knows whether or not to try and reconstruct a path. bool error = true; while( open.size() > 0 ) { //The current point is the first entry in the open list. cur = open.at(0); if( cur->getPos() == end.getPos() ) { error = false; break; } //Add in all the neighbors of the current point. for( int y = -1; y <= 1; y++ ) { for( int x = -1; x <= 1; x++ ) { int curX = cur->getPos().x+x; int curY = cur->getPos().y+y; int movCost = 10; //If it is a diagonal, make it cost 14 instead of 10. if( (y == -1 && x == -1)|| (y == 1 && x == -1)|| (y == -1 && x == 1)|| (y == 1 && x == 1)) { movCost = 14; //continue; } Coord temp( curX, curY ); bool make = true; //If it is outside the range of the map, continue. if( curY >= grid.size() || curX >= grid.size() ) { continue; } /* These two loops are to check whether or not the point's neighbors already exist. This feels really sloppy to me. Please tell me if there is a better way. */ for( int i = 0; i < open.size(); i++ ) { if( temp == open.at(i)->getPos() ) { make = false; break; } } for( int i = 0; i < closed.size(); i++ ) { if( temp == closed.at(i)->getPos() ) { make = false; break; } } //If the point in the map is a zero, then it is a wall. Continue. if( (grid.at(temp.x).at(temp.y) == 0 ) || ( temp.x<0 || temp.y < 0 ) ) { continue; } //If it is allowed to make a new point, it adds it to the open list. if( make ) { int gScore = cur->getCost(); int hScore = manhattan( end.getPos(), Coord( curX, curY ) ); int tileCost = grid[curX][curY]; int fScore = gScore+hScore+tileCost+movCost; open.push_back( new Point( curX, curY, fScore, cur ) ); } } } //It then pushes back the current into the closed set as well as erasing it from the open set. closed.push_back( cur ); open.erase( open.begin() ); //Heapsort works, guranteed. Not sure if it's a stable sort, though. From what I can tell that shouldn't matter, though. open = heapsort( open ); } std::vector<Coord> path; if( error ) { return path; } //Reconstruct a path by tracing through the parents. while( cur->getParent() != nullptr ) { path.push_back( cur->getPos() ); cur = cur->getParent(); } path.push_back( cur->getPos() ); return path; }
void sort(short int *values, unsigned char n) { if(n != 0) heapsort(values, n); }
// This method fills the symmetric sparse structure // so that the matrix is not any more in upper or lower // triangular form. void CSRdouble::fillSymmetric() { int nonzeros; int n = this->nrows; int* prows = this->pRows; int* pcols = this->pCols; double* pdata = this->pData; vector<vector<double> > vA(n); vector<vector<int> > vcols(n); int i; for (i = 0; i < n; i++) { for (int index = prows[i]; index < prows[i+1]; index++) { int j = pcols[index]; vcols[i].push_back(j); double a_ij = pdata[index]; vA[i].push_back(a_ij); // this is the j column in the i-th row; now we need to find the // i-th column in the j-th row; If it is there we do nothing; if // not then we need to add it if (i != j) { bool found = false; for (int k = prows[j]; k < prows[j+1]; k++) { int col = pcols[k]; if (col == i) { found = true; break; } } if ( !found ) { //cout << "The matrix is not Structurally Symmetric\n"; vcols[j].push_back(i); vA[j].push_back(a_ij); } } } } int* ia = new int[n+1]; ia[0] = 0; for (i = 0; i < n; i++) { ia[i+1] = ia[i] + vcols[i].size(); } nonzeros = ia[n]; int* ja = new int[nonzeros]; double* a = new double[nonzeros]; for (i = 0; i < n; i++) { int index = ia[i]; int entries = vcols[i].size(); for (int j = 0; j < entries; j++) { ja[index + j] = vcols[i][j]; a[index + j] = vA[i][j]; } if (entries > 1) heapsort(entries, &ja[index], &a[index]); } delete[] pRows; delete[] pCols; delete[] pData; make(n, n, nonzeros, ia, ja, a); matrixType = NORMAL; }
struct node *delmin(struct node *f[],int n) { heapsort(f,n); return f[n-1]; }
int main(int argc, char ** argv){ long ierr, n, ntot; int myid, mysize; long icheck,isort,iprint; double t1, t2, tdiff; long * ia = (long *) malloc(isize*sizeof(long)); long * index = (long *) malloc(isize*sizeof(long)); memset(ia,0,isize); memset(index,0,isize); //********************************************************************** // Initialization //********************************************************************** t1 = omp_get_wtime(); isort = 0; iprint = 1; ntot = isize; //********************************************************************** // Initialize MPI and Get myrank: //********************************************************************** MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&mysize); //********************************************************************** // Get mysize: //********************************************************************** MPI_Comm_rank(MPI_COMM_WORLD,&myid); //********************************************************************** // worker task //********************************************************************** long elements_to_print[30]; if (myid == 0){ printf("myid = %d of total size = %d\n",myid,mysize); //********************************************************************** // open file and read ia array //***********************************************************************/ printf("reading input from file hw7.in\n"); readfile("hw7.in",ia); // =================== IMPORT THE FILE hw7.in ========================== printf("File opened successfully. Reading input values\n"); // read (1,*,err = 30) ia // prlong *,isize,' longeger values read successfully' // go to 40 // // 30 prlong *,'Error reading input values --- Stopping!' // go to 999 //********************************************************************** // calling heapsort //********************************************************************** printf("myid = %d; calling heapsort\n",myid); heapsort(ia, ntot, isort); /*********************************************************************** // check that data are in ascending order ***********************************************************************/ icheck = 0; if(isort == 0){ //=================== ascending ======================================== for(n = 1; n < ntot;++n){ if (ia[n] < ia[n-1]){ printf("Error in sorted order at n = %d\n",n); icheck = 1; }; }; }else{ //==================== descending ====================================== for(n = 1; n < ntot;++n){ if (ia[n] > ia[n]){ printf("Error in sorted order at n = %d \n",n); icheck = 1; }; }; }; /*********************************************************************** // termination test ***********************************************************************/ if(icheck == 0){ printf("Array sorted correctly\n"); }else{ printf("Array sorted incorrectly\n"); }; /*********************************************************************** // prlong sorted indices ***********************************************************************/ long element_count=0; if(iprint == 1){ /*********************************************************************** // prlong 1st 10 elements ***********************************************************************/ for(n = 0; n< 10;++n){ //elements_to_prlong.push_back(ia[index[n]]); elements_to_print[element_count] = ia[n]; ++element_count; }; /*********************************************************************** // prlong middle 10 elements ***********************************************************************/ for(n = ((ntot/2)-5); n< ((ntot/2)+5);++n){ //elements_to_prlong.push_back(ia[index[n]]); elements_to_print[element_count] = ia[n]; ++element_count; } /*********************************************************************** // prlong last 10 elements ***********************************************************************/ for(n = (ntot-10); n < ntot;++n){ //elements_to_prlong.push_back(ia[index[n]]); elements_to_print[element_count] = ia[n]; ++element_count; }; }; /***************************************************** get total time ******************************************************/ t2 = omp_get_wtime(); tdiff = t2 - t1; printf("\tPrintng 1st 10 elements\n"); long j; for(j=0;j<10;++j){ printf("\t%d, \t%d\n",j+1,elements_to_print[j]); } printf("\tPrintng middle 10 elements\n"); for(j=10;j<20;++j){ printf("\t%d, \t%d\n",j+(ntot)/2-15+1,elements_to_print[j]); } printf("\tPrintng last 10 elements\n"); for(j=20;j<30;++j){ printf("\t%d, \t%d\n",j+ntot-30+1,elements_to_print[j]); } printf("Total wall clock time = %f (secs) --- Stopping!\n",tdiff); }else{ //********************************************************************** //********************************************************************** // worker tasks //********************************************************************** //********************************************************************** printf("myid = %d of total size = %d\n",myid,mysize); } // // terminate MPI // MPI_Finalize(); // //3000 format (1x,'Calling hsort: isort,iprint =',2(1x,i5)) //3001 format (5x,'Before sort: printing ia with',i12,' elements') //3002 format (5x,'Final: printing ia with',i12,' elements') //3003 format (5x,'Printing 1st 10 elements') //3004 format (5x,'Printing middle 10 elements') //3005 format (5x,'Printing last 10 elements') };
int main() { heapsort(); return(0); };
// This function build a node of the kdtree with the // points indexed by pidx with length "len" // sortidx is a pre-computed array using the heapsort // algorithm above int KDTree::build_kdtree(int **sortidx, int dim, int *pidx, int len, AABB ¤tBB) { static const Vec3 BufferOffset( KD_SPLIT_BUFFER_SIZE, KD_SPLIT_BUFFER_SIZE, KD_SPLIT_BUFFER_SIZE ); AABB b1, b2; int ncnt = nodeMemCnt; struct KDTreeNode *node = node_alloc(); node->bounds.Set( currentBB.m_Bounds[0] - BufferOffset, currentBB.m_Bounds[1] + BufferOffset ); node->axis = dim; if (len <= m_KDCellSize && m_KDCellSize == 1 ) { node->leftIdx = -1; node->rightIdx = -1; node->pntidx = pidx[0]; node->key = 0; node->bounds.Set( currentBB.m_Bounds[0] - BufferOffset, currentBB.m_Bounds[1] + BufferOffset ); //add objects to this node if( m_NodeCreationCallBack ) { (*m_NodeCreationCallBack)( node ); } return ncnt; } // If not, we must make a node int pivot = -1; int lcnt = 0, rcnt = 0; int *larray, *rarray; // Find the pivot (index of median point of available // points on current dimension). // If heapsorting the current list of points is quicker than // iterating through all the points, just do that instead // (heapsort if of order n*log(n) // This test could probably use some fine tuning if((double)len*log((double)len) < npoints) { heapsort(dim,pidx,len); larray = pidx; rarray = pidx+len/2; pivot = pidx[len/2]; lcnt = len/2; rcnt = len/2 + (len%2==0 ? 0 : 1); } else { // Use the previously calculated sort index // to make this a process linear in npoints // This gets a little confusing, but it works. // Sortidx:: sortidx[dim][idx] = val // idx = the index to the point // val = the order in the array int *parray = workArr; // Setting parray to -1 indicates we are not using // the point for (int i = 0; i < npoints; i++) parray[i] = -1; // Populate "parray" with the points that we // are using, indexed in the order they occur // on the current dimension for (int i = 0; i < len; i++) parray[sortidx[dim][pidx[i]]] = pidx[i]; int cnt = 0; larray = int_alloc(len/2+1); rarray = int_alloc(len/2+1); // The middle valid value of parray is the pivot, // the left go to a node on the left, the right // go to a node on the right. for (int i = 0; i < npoints; i++) { if (parray[i] == -1) continue; if (cnt == len / 2) { pivot = parray[i]; rarray[rcnt++] = parray[i]; } else if (cnt > len / 2) rarray[rcnt++] = parray[i]; else larray[lcnt++] = parray[i]; cnt++; if(cnt>len) break; } } if (len <= m_KDCellSize && m_KDCellSize > 1 ) { node->leftIdx = -1; node->rightIdx = -1; if( m_KDCellSize > 1 ) { for( int i = 0; i < len; i++ ) { node->fattyCellData.push_back( pidx[ i ] ); } } node->pntidx = pivot; node->key = 0; node->bounds.Set( currentBB.m_Bounds[0] - BufferOffset, currentBB.m_Bounds[1] + BufferOffset ); //add objects to this node if( m_NodeCreationCallBack ) { (*m_NodeCreationCallBack)( node ); } return ncnt; } // Create the node node->pntidx = -1; node->key = points[pivot*ndim+dim] + KEY_EPSILON; //calculate bounding boxes if( m_NodeCreationCallBack ) { b1 = b2 = currentBB; //b1 is for left, b2 for right //split on the x axis int realDim = dim%ndim; if( realDim == 0 ){ b1.m_Bounds[1].x = node->key; //set tmax bounds of left bb to be new split point b2.m_Bounds[0].x = node->key; //set tmin bounds of right bb to be new split point }else if( realDim == 1 ) { b1.m_Bounds[1].y = node->key; //set tmax bounds of left bb to be new split point b2.m_Bounds[0].y = node->key; //set tmin bounds of right bb to be new split point }else if( realDim == 2 ) { b1.m_Bounds[1].z = node->key; //set tmax bounds of left bb to be new split point b2.m_Bounds[0].z = node->key; //set tmin bounds of right bb to be new split point } } // Create nodes to the left node->leftIdx = build_kdtree(sortidx, (dim + 1) % ndim, larray, lcnt, b1); // Create nodes to the right node->rightIdx = build_kdtree(sortidx, (dim + 1) % ndim, rarray, rcnt, b2); return ncnt; } // end of build_kdtree
typedef unsigned long long my_sorted_t; typedef std::vector<my_sorted_t> my_vector_t; static struct { const char *name; std::function<void (my_vector_t &)> fun; } g_tests[] = { {"STL vector sort", [] (my_vector_t &v) { std::sort (v.begin (), v.end ()); }}, {"Vector heapsort", [] (my_vector_t &v) { heapsort (v); }}, {"STL qsort", [] (my_vector_t &v) { qsort (v.data (), v.size (), sizeof *(v.data ()), int_compare<my_sorted_t>); }}, {"8-bit radixsort", [] (my_vector_t &v) { radixsort_8 (v.data (), v.size (), sizeof *(v.data ())); }} }; template<typename T, typename U> static int measure (const std::vector<T> &v, const std::vector<T> &ref, U f) {