Example #1
0
int main(int argc, char *argv[]) {
  Vector v1 = read_input_file(argv[1]);
  merge_sort(v1.integers, v1.size);
  free_vector(v1);
  return 0;
}
Example #2
0
/**
 * Example code for:
 * (1) reading a file of strings into an array
 * (2) using merge-sort to sort them
 * (3) printing the sorted lines
 */
int main(int argc, char * * argv)
{
    // The file we read from.
    FILE * fp = NULL;

    // Will read the file line-by-line into this buffer
    size_t buffer_len = 1024;
    char * buffer = malloc(buffer_len * sizeof(char));

    // Parse input arguments
    if(argc != 2) {
	print_usage(argv[0]);
	return EXIT_FAILURE;
    }
    
    if(strcmp(argv[1], "--help") == 0) {
	print_usage(argv[0]);
	return EXIT_SUCCESS;
    } else {
	const char * filename = argv[1];
	fp = fopen(filename, "r");
	if(fp == NULL) {
	    fprintf(stderr, "Failed to open file '%s', aborting\n", filename);
	    return EXIT_FAILURE;
	}
    }

    // How many lines of input are there?
    int n_lines = 0;

    // Read the file line-by-line. Lookup the man-page of getline for details.
    while(getline(&buffer, &buffer_len, fp) != -1)
	n_lines++;

    // Create an array of strings
    char * * strArr = malloc(n_lines * sizeof(char *));

    // Initialize the contents of strArr by re-reading the entire file.
    fseek(fp, 0, SEEK_SET);
    int ind = 0;
    while(getline(&buffer, &buffer_len, fp) != -1)
	strArr[ind++] = strdup(buffer);

    // Sort strArr
    merge_sort(strArr, n_lines, strcmp);

    // Print the result
    for(ind = 0; ind < n_lines; ++ind) {
	const char * s = strArr[ind];
	printf("%s", s);
	int len = strlen(s);
	if(len > 0 && s[len-1] != '\n')
	    printf("\n"); // make sure there's always a new-line character
    }

    // Cleanup resources
    fclose(fp);
    free(buffer);
    for(ind = 0; ind < n_lines; ++ind)
	free(strArr[ind]);
    free(strArr);

    return EXIT_SUCCESS;
}
Example #3
0
int main() {
    int sz = SIZE(arr);
    merge_sort(arr,sz);
    FO(i,sz) {
        printf("%d\n",arr[i]);
    }
void merge_sort(task_t **tasks, int left, int right) {
	pthread_t left_thread;
	int thread_created = 0;
	// Only split up when two or more elements
	if(left >= 2) {
		int newleft = left/2;
		int newright = left-newleft;
		if (thread_count < MAX_THREAD_COUNT) {
			pthread_mutex_lock(&mutex);
			// Look if still under the thread limit
			if (thread_count < MAX_THREAD_COUNT) { 
				thread_count++;
				pthread_mutex_unlock(&mutex);
				// Left gets a new thread
				merge_args args;
				args.tasks = tasks;
				args.left = newleft;
				args.right = newright;

				// printf("Creating new thread! Current count: %d \n", thread_count);
				thread_created = 1;
				int thread_result = pthread_create(&left_thread, NULL, merge_thread_sort, &args);
				
				//ERROR HANDLING
				if (thread_result == EAGAIN) {
					printf("THREAD ERROR: %d, NO RESOURCES LEFT IN SYSTEM",thread_result);
					// exit(127);
					thread_created = 0;
				} else if (thread_result == EINVAL) {
					printf("THREAD ERROR: %d, EINVAL",thread_result);
					exit(127);
				} else if (thread_result == EPERM) {
					printf("THREAD ERROR: %d, EPERM",thread_result);
					exit(127);
				}
			} else {
				pthread_mutex_unlock(&mutex);
			}
		}
		if(thread_created == 0) {
			// pthread_mutex_unlock(&mutex);
			// printf("Max thread reached, do it yourself! Current count: %d \n", thread_count);
			
			merge_sort(tasks, newleft, newright);
		}
	}
	
	// Only split up when two or more elements
	if(right >= 2) {
		int newleft = right/2;
		int newright = right-newleft;
		// Change the pointer to a new element within the array (tasks+left)
		merge_sort(tasks+left, newleft, newright);
	}
	// Wait for left thread to finish
	if (thread_created)
		pthread_join(left_thread, NULL);

	// Merge!
	merge(tasks, left, right);
}
int main(void){
    int *vetor1,*q, *vetorinverso;
	  int cont, cont2, media, cont3, cont4, cont5;
    float tempo1, tempo2, tempo3, iteracoes=10;
  	int MAX=1000;
  	clock_t Ti, Tf;
  	float DeltaT;
    cont5=0;

    FILE *txt;


    txt=fopen("data2.txt","a+");


	  srand((unsigned)time(NULL));
    fprintf(txt,"tamanho,quicksort_ordenacao,quicksort_jaordenado,quicksort_decrescente,mergesort_ordenacao,mergesort_jaordenado,mergesort_decrescente,bublesort_ordenacao,bublesort_jaordenado,bublesort_decrescente\n");
    for(cont=0;cont<6;cont++){
      vetor1=malloc(sizeof(int) * MAX);
      vetorinverso=malloc(sizeof(int) * MAX);
      tempo1=0;
      tempo2=0;
      tempo3=0;
      for(cont2=0;cont2<iteracoes;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();
        bubblesort(q,MAX-1);
        Tf=clock();
        DeltaT=Tf-Ti;
        DeltaT=DeltaT/1000;
        tempo3=tempo3+DeltaT;

      }
      cont4=0;
      for(cont3=MAX-1;cont3>=0;cont3--){
          vetorinverso[cont4]=cont3;
          cont4++;
         }
      fprintf(txt,"%d,",MAX);
      //printf("quicksort;");
      Ti=clock();
      quickSort(q,0,MAX-1);
      Tf=clock();
      DeltaT=Tf-Ti;
      DeltaT=DeltaT/1000;
      fprintf(txt,"%f,",(tempo1/iteracoes));
      fprintf(txt,"%f,",DeltaT);
      free(q);
      q=copiavetor(vetorinverso,MAX);
      Ti=clock();
      quickSort(q,0,MAX-1);
      Tf=clock();
      DeltaT=Tf-Ti;
      DeltaT=DeltaT/1000;
      fprintf(txt,"%f,",DeltaT);

      //printf("mergesort\n");
      Ti=clock();
      merge_sort(q,MAX-1);
      Tf=clock();
      DeltaT=Tf-Ti;
      DeltaT=DeltaT/1000;
      fprintf(txt,"%f,",tempo2/iteracoes);
      fprintf(txt,"%f,",DeltaT);
      free(q);
      q=copiavetor(vetorinverso,MAX);
      Ti=clock();
      merge_sort(q,MAX-1);
      Tf=clock();
      DeltaT=Tf-Ti;
      DeltaT=DeltaT/1000;
      fprintf(txt,"%f,",DeltaT);

      //printf("bublesort\n");
      Ti=clock();
      bubblesort(q,MAX-1);
      Tf=clock();
      DeltaT=Tf-Ti;
      DeltaT=DeltaT/1000;
      fprintf(txt,"%f,",tempo3/iteracoes);
      fprintf(txt,"%f,",DeltaT);
      free(q);
      q=copiavetor(vetorinverso,MAX);
      Ti=clock();
      bubblesort(q,MAX-1);
      Tf=clock();
      DeltaT=Tf-Ti;
      DeltaT=DeltaT/1000;
      fprintf(txt,"%f,",DeltaT);
      free(q);
      free(vetor1);
      free(vetorinverso);
      if(cont5==0){
        MAX=5000;
      }
      if(cont5==1){
        MAX=10000;
      }
      if(cont5==2){
        MAX=100000;
      }
      if(cont5==3){
        MAX=500000;
      }
      if(cont5==4){
        MAX=1000000;
      }
      cont5++;
      fprintf(txt,"\n");
    }
    return 0;
}
int main(){
	int arr[10] = {15,25,31,21,54,62,41,23,35,45};
	int buf[10];
	merge_sort(arr, 0, 9, buf);
	return 0;
}
Example #7
0
File: fl.c Project: soxhc/linux-ls
void fl_sort(struct filelist *head, int (*cmp)(const struct filelist *, const struct filelist *))
{
        assert(head != NULL && cmp != NULL);
        if (!fl_empty(head))
                head->fl_next = merge_sort(head->fl_next, cmp);
}
int
main (int argc, char *argv[]) {
        // Size of int to be tested
        size_t n = 100000;

        // Checks if test should be ran with custom array size
        if (argc > 1) {
                int are_all_digits = 1;

                char *cp;
                for (cp = argv[1]; cp && *cp == ' '; ++cp)
                        // Checks if char is not a digit
                        if (!isdigit(*cp)) {
                                are_all_digits = 0;
                                break;
                        }

                // Checks if all chars were digits
                if (are_all_digits)
                        // Changes the n variable to first program arg
                        sscanf(argv[1], "%zd", &n);
        }

        // For mesuring algorithm execution time
        clock_t start, end;
        double cpu_time_used;

        // For generating random numbers
        srand(time(NULL));

        int *A = malloc(sizeof(int) * n);

        // Fills the firt array with random numbers
        int i;
        for (i = 0; i < n; ++i)
                A[i] = rand();

        // Copies first array to seccond array
        int *B = malloc(sizeof(int) * n);
        memcpy(B, A, sizeof(int) * n);

        // Sorts the first array using qsort  function
        qsort(A, n, sizeof(int), cmpfunc);

        // Sorts the second array using merge_sort function
        // Calculates execution time for merge_sort function
        start = clock();
        merge_sort(B, n);
        end = clock();
        cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

        // Checks if two arrays are exactly equal
        int failure = memcmp(A, B, n * sizeof(int));

        if (failure)
                printf(KRED "Algorithm Test failed!\n" RESET);
        else
                printf(KGRN "Algorithm Test succeeded!\n" RESET);

        printf(KBLU "Algorithm execution seconds: %lf\n" RESET, cpu_time_used);

        // Frees two arrays memory
        free(A);
        free(B);
        return failure;
}
int main(int argc, char *argv[]){
   double  redshift;
   char    filename_in[MAX_FILENAME_LENGTH];
   char    filename_out[MAX_FILENAME_LENGTH];
   char    filename_cosmology[MAX_FILENAME_LENGTH];
   double  box_size;
   double  lM_min,dlM;
   char   *line=NULL;
   size_t  line_length=0;
   int     M_column;
   int     n_bins;
   int     flag_log;
 
   // Initialization -- MPI etc.
   SID_init(&argc,&argv,NULL,NULL);
   if(argc!=11)
     SID_trap_error("Incorrect syntax.",ERROR_SYNTAX);

   // Parse arguments
   strcpy(filename_in, argv[1]);
   strcpy(filename_out,argv[2]);
   redshift=(double)atof(argv[3]);
   strcpy(filename_cosmology,argv[4]);
   box_size=(double)atof(argv[5]);
   M_column=(int)   atoi(argv[6]);
   flag_log=(int)   atoi(argv[7]);
   lM_min  =(double)atof(argv[8]);
   dlM     =(double)atof(argv[9]);
   n_bins  =(int)   atoi(argv[10]);

   SID_log("Producing a mass function for ascii file {%s}...",SID_LOG_OPEN|SID_LOG_TIMER,filename_in);
 
   // Initialize cosmology
   cosmo_info *cosmo;
   read_gbpCosmo_file(&cosmo,filename_cosmology);
   double h_Hubble=((double *)ADaPS_fetch(cosmo,"h_Hubble"))[0];

   // Open file
   FILE *fp_in;
   if((fp_in=fopen(filename_in,"r"))==NULL)
      SID_trap_error("Could not open {%s} for reading.",ERROR_IO_OPEN,filename_in);

   // Allocate memory for the data. Read it and sort it in ascending order 
   SID_log("Reading data...",SID_LOG_OPEN|SID_LOG_TIMER);
   int     n_data_in=count_lines_data(fp_in);
   SID_log("(%d items)...",SID_LOG_CONTINUE,n_data_in);
   double *data  =(double *)malloc(sizeof(double)*n_data_in);
   int n_data=0;
   for(int i=0;i<n_data_in;i++){
     double data_in;
     grab_next_line_data(fp_in,&line,&line_length);
     grab_double(line,M_column,&data_in);
     if(!flag_log)
        data_in=take_log10(data_in);
     if(data_in>=lM_min)
        data[n_data++]=data_in;
   }
   SID_log("(%d will be used)...",SID_LOG_CONTINUE,n_data);
   fclose(fp_in);
   SID_free(SID_FARG line);
   SID_log("Done.",SID_LOG_CLOSE);

   // Perform sort
   SID_log("Sorting data...",SID_LOG_OPEN|SID_LOG_TIMER);
   merge_sort(data,n_data,NULL,SID_DOUBLE,SORT_INPLACE_ONLY,SORT_COMPUTE_INPLACE);
   SID_log("Done.",SID_LOG_CLOSE);

   // Compile histogram
   SID_log("Computing mass function...",SID_LOG_OPEN|SID_LOG_TIMER);
   double *bin       =(double *)SID_malloc(sizeof(double)*(n_bins+1));
   double *bin_median=(double *)SID_malloc(sizeof(double)*n_bins);
   int    *hist      =(int    *)SID_calloc(sizeof(int)   *n_bins);
   double  lM_bin_min=lM_min;
   double  lM_bin_max=lM_min;
   int     i_data_lo=-1;
   int     i_data_hi=-1;
   int     i_bin =0;
   int     i_data=0;
   for(i_bin=0;i_bin<n_bins;i_bin++){
     lM_bin_min=lM_bin_max;
     lM_bin_max=lM_min+((double)(i_bin+1))*dlM;
     bin[i_bin]=lM_bin_min;
     i_data_lo=i_data;
     i_data_hi=i_data;
     while(data[i_data]<lM_bin_max && i_data<n_data){
        hist[i_bin]++;
        i_data_hi=i_data;
        i_data++;
        if(i_data>=n_data) break;
     }
     int i_data_mid=(i_data_lo+i_data_hi)/2;
     if(hist[i_bin]>0){
       if(hist[i_bin]%2)
         bin_median[i_bin]=data[i_data_mid];
       else
         bin_median[i_bin]=0.5*(data[i_data_mid]+data[i_data_mid+1]);
     }
     else
        bin_median[i_bin]=0.5*(lM_bin_max+lM_bin_min);
   }
   bin[i_bin]=lM_bin_max;
   SID_log("Done.",SID_LOG_CLOSE);

   // Write mass function
   FILE *fp_out;
   if((fp_out=fopen(filename_out,"w"))==NULL){
     fprintf(stderr,"Error opening output file {%s}.\n",filename_out);
     SID_free(SID_FARG data);
     return(1);
   }
   SID_log("Writing results to {%s}...",SID_LOG_OPEN|SID_LOG_TIMER,filename_out);
   double box_volume=box_size*box_size*box_size;
   fprintf(fp_out,"# Mass function for column %d in {%s}\n",M_column,filename_in);
   fprintf(fp_out,"# Column (01): M_lo     [source units]\n");
   fprintf(fp_out,"#        (02): M_median [source units]\n");
   fprintf(fp_out,"#        (03): M_hi     [source units]\n");
   fprintf(fp_out,"#        (04): No. in bin\n");
   fprintf(fp_out,"#        (05): MFn (per unit volume, per dlogM)\n");
   fprintf(fp_out,"#        (06): +/- MFn\n");
   fprintf(fp_out,"#        (07): Sheth & Tormen MFn\n");
   fprintf(fp_out,"#        (08): Watson MFn\n");
   fprintf(fp_out,"#        (09): No. w/ M>M_lo\n");
   fprintf(fp_out,"#        (10): Cumulative MFn (per unit volume)\n");
   fprintf(fp_out,"#        (11): +/- Cumulative MFn\n");
   fprintf(fp_out,"#        (12): Sheth & Tormen Cumulative MFn\n");
   fprintf(fp_out,"#        (13): Watson Cumulative MFn\n");
   double M_sol_inv_h=M_SOL/h_Hubble;
   double Mpc_inv_h  =M_PER_MPC/h_Hubble;
   for(int i=0;i<n_bins;i++){
     double dn_dlogM_theory_1=mass_function(take_alog10(bin_median[i])*M_sol_inv_h,
                                            redshift,
                                            &cosmo,
                                            MF_ST)*pow(Mpc_inv_h,3.0);
     double n_theory_1=mass_function_cumulative(take_alog10(bin[i])*M_sol_inv_h,
                                                redshift,
                                                &cosmo,
                                                MF_ST)*pow(Mpc_inv_h,3.0);
     double dn_dlogM_theory_2=mass_function(take_alog10(bin_median[i])*M_sol_inv_h,
                                            redshift,
                                            &cosmo,
                                            MF_WATSON)*pow(Mpc_inv_h,3.0);
     double n_theory_2=mass_function_cumulative(take_alog10(bin[i])*M_sol_inv_h,
                                                redshift,
                                                &cosmo,
                                                MF_WATSON)*pow(Mpc_inv_h,3.0);
     // Compute cumulative histogram
     int cumulative_hist=0;
     for(int j_bin=i;j_bin<n_bins;j_bin++)
        cumulative_hist+=hist[j_bin];
     fprintf(fp_out,"%11.4le %11.4le %11.4le %6d %11.4le %11.4le %10.4le %10.4le %6d %10.4le %10.4le %10.4le %10.4le\n",
             bin[i],
             bin_median[i],
             bin[i+1],
             hist[i],
             (double)(hist[i])/(box_volume*dlM),
             sqrt((double)(hist[i]))/(box_volume*dlM),
             dn_dlogM_theory_1,dn_dlogM_theory_2,
             cumulative_hist,
             (double)(cumulative_hist)/box_volume,
             sqrt((double)(cumulative_hist))/box_volume,
             n_theory_1,n_theory_2);
   }
   fclose(fp_out);
   SID_log("Done.",SID_LOG_CLOSE);

   // Free allocated memory
   SID_free(SID_FARG data);
   SID_free(SID_FARG bin);
   SID_free(SID_FARG bin_median);
   SID_free(SID_FARG hist);
  
   SID_log("Done.",SID_LOG_CLOSE);
   SID_exit(ERROR_NONE);
}
Example #10
0
void Mergesort(long long* arr,unsigned long long n)
{
	merge_sort(arr,0,n-1);
		 	
}
vector<Result*> QueryProcessor::sortResults(vector<Page*>& unsortedResults)
{
  vector<double>resultsinversefreq;
  //if there are AND arguments
  if (currentQ->getandArgs().size() > 0)
  {
    //for each Page* object in the unsorted results vector
    for (auto e:unsortedResults)
    {
      //cout << "processing " << e->getTitle() << endl;
      double freq = 0;
      double sumwords = 0;
      //for each keyword string in the page object
      for (int i = 0; i < e->getKeywords().size(); i++)
      {
        //for each of the and arguments
        for (auto arg: currentQ->getandArgs())
        {
          if (arg == e->getKeywordAtIndex(i))
          {
            freq += e->getFrequency(i); //argument found in page
            break;
          }
        }
        sumwords+=1; //incremenet number of words
      }

      //do the math
      resultsinversefreq.push_back(freq/sumwords);
    }
  }
  else if(currentQ->getorArgs().size() > 0)
  {
    for (auto e: unsortedResults)
    {
      double freq = 0;
      double sumwords = 0;
      //for each keyword string in the page object
      for (int i = 0; i < e->getKeywords().size(); i++)
      {
        //for each of the or arguments
        for (auto arg: currentQ->getorArgs())
        {
          if (arg == e->getKeywordAtIndex(i))
          {
            freq += e->getFrequency(i); //argument found in page
            break;
          }
        }
        sumwords+=1; //incremenet number of words
      }

      //do the math
      resultsinversefreq.push_back(freq/sumwords);
    }
  }
  else //if there is only one search term
  {
    cout << currentQ->getnormArgs()[0] << endl;
    //for each Page* object in the unsorted results vector
    for (auto e:unsortedResults)
    {
      double freq = 0;
      double sumwords = 0;
      //for each keyword string in the page object
      for (int i = 0; i < e->getKeywords().size(); i++)
      {
        //cout << e->getKeywordAtIndex(i) << "\t" << e->getFrequency(i) << endl;
        if (currentQ->getnormArgs()[0] == e->getKeywordAtIndex(i))
        {
          freq += e->getFrequency(i); //argument found in page
          break;
        }
        sumwords+=1; //incremenet number of words
      }
      //do the math
      resultsinversefreq.push_back(freq/sumwords);
    }
  }
  vector<Result*>results;
  //now sort
  for (int i = 0; i < unsortedResults.size(); i++)
  {
    Result* rs = new Result(unsortedResults[i], resultsinversefreq[i]);
    results.push_back(rs);
  }

  //sort the results
  if (results.size() > 1)
    results = merge_sort(results);

  if (results.size() > 15)
    results.erase(results.begin()+15, results.end());


  return results;
}
Example #12
0
int main (int argc, char * argv[])
{

	struct node_list_in * list_in;
	struct chain_context chain;
	struct chain_node * node;
	struct chain_node * nodes;
	uint32_t A, B, C, D;
	int i;

	/************************
	* DEAL WITH INPUT       *
	************************/

	if (argc != 8)
	{
		//             0  1               2               3         4                  5            6         7
		printf("Usage: %s <sorted rtable> <hash_function> <charset> <plaintext_length> <chain_size> <table_i> <hash>\n", argv[0]);
		exit(0);
	}
	
	if (strcmp(argv[2], "nt") == 0)
	{
		hash_function = nt_hash;
		reduce_function = nt_reduce;
	}
	else
	{
		printf("Invalid hash function\n");
		exit(0);
	}
	
	if (strcmp(argv[3], "az") == 0)
		chain.charset = az;
	else if (strcmp(argv[3], "az09") == 0)
		chain.charset = az09;
	else if (strcmp(argv[3], "azAZ09") == 0)
		chain.charset = azAZ09;
	else if (strcmp(argv[3], "azAZ09special") == 0)
		chain.charset = azAZ09special;
	else
	{
		printf("Invalid hash function\n");
		exit(0);
	}
	
	/*********************************
	* INIT CRAP                      *
	*********************************/
	
	A = hex_string_to_uint32(&(argv[7][0]));
	B = hex_string_to_uint32(&(argv[7][8]));
	C = hex_string_to_uint32(&(argv[7][16]));
	D = hex_string_to_uint32(&(argv[7][24]));

	chain.chain = 0;
	chain.chain_size = atoi(argv[5]);
	chain.table = atoi(argv[6]);
	chain.plaintext_length = atoi(argv[4]);
	chain.charset = az;
	memset(chain.plaintext, 0, 128);
	
	printf("chain.chain %d\tchain.plaintext_length %d\n", chain.chain, chain.plaintext_length);
	printf("chain.table %d\tchain.chain_size %d\n", chain.table, chain.chain_size);
	printf("starting hash %08x%08x%08x%08x\n", A, B, C, D);
	
	nodes = malloc(sizeof(struct chain_node) * chain.chain_size);
	nodes[0].a = A;
	nodes[0].b = B;
	nodes[0].c = C;
	nodes[0].d = D;
	
	/**********************************************
	* CONSTRUCT CHAINS TO FIND HASHES TO LOOK FOR *
	**********************************************/
	
	printf("generating chains... ");
	for (i = 1; i < chain.chain_size; i++)
	{
		chain.A = A;
		chain.B = B;
		chain.C = C;
		chain.D = D;
		create_context_chain(&chain, i);
		nodes[i].a = chain.A;
		nodes[i].b = chain.B;
		nodes[i].c = chain.C;
		nodes[i].d = chain.D;
	}
	printf("done\n");
	
	printf("merge_sort... ");
	merge_sort(nodes, chain.chain_size);
	printf("done\n");
	
	#if RC_DEBUG == 1
	printf("Testing sorted list\n");
	for (i = 0; i < chain.chain_size; i++)
	{
		printf("%08x%08x%08x%08x\n", nodes[i].a, nodes[i].b, nodes[i].c, nodes[i].d);
	}
	#endif
	
	/**************************
	* SEARCH FOR THOSE HASHES *
	**************************/
	
	i = 0;
	list_in = open_node_list_in(argv[1]);
	if (list_in == NULL)
	{
		printf("failed to open %s\n", argv[1]);
		exit(0);
	}
	node = next_node_list_in(list_in);
	
	printf("search for hash\n");
	while (node != NULL)
	{
		// skip nodes in file until we get to the next node in nodes
		// to look for (nodes is sorted)
		while (compare_nodes(node, &nodes[i]) < 0)
		{
			node = next_node_list_in(list_in);
			if (node == NULL)
				break;
		}
		
		if (node != NULL)
		{
			if (compare_nodes(node, &nodes[i]) == 0)
			{
				chain.chain = node->chain_id;
				if (find_hash_in_chain(&chain, A, B, C, D) == 1)
				{
					return 1;
				}
			}
		}
		
		i++;
		
	}
		
	close_node_list_in(list_in);;
	
	return 1;

}
Example #13
0
struct listNode* merge_sort(struct listNode* x)
/*@ rule <k> $ => return ?x; ...</k>
         <heap>... list(x)(A) => list(?x)(?A) ...</heap>
    if isSorted(?A) /\ seq2mset(A) = seq2mset(?A) */
{
  struct listNode* p;
  struct listNode* y;
  struct listNode* z;

  if (x == NULL || x->next == NULL)
    return x;

  y = NULL;
  z = NULL;
  /*@ inv <heap>... list(x)(?A), list(y)(?B), list(z)(?C) ...</heap>
          /\ seq2mset(A) = seq2mset(?A) U seq2mset(?B) U seq2mset(?C)
          /\ (len(?B) = len(?C) \/ len(?B) = len(?C) + 1 /\ x = 0) */
  while (x != NULL) {
    struct listNode* t;

    t = x;
    x = x->next;
    t->next = y;
    y = t;

    if (x != NULL) {
      t = x;
      x = x->next;
      t->next = z;
      z = t;
    }
  }

  y = merge_sort(y);
  z = merge_sort(z);

  if (y->val < z->val) {
    x = y;
    p = y;
    y = y->next;
  }
  else {
    x = z;
    p = z;
    z = z->next;
  }
  /*@ inv <heap>...lseg(x,p)(?A1),p|->[?v,?n],list(y)(?B),list(z)(?C) ...</heap>
          /\ seq2mset(A) = seq2mset(?A1 @ [?v]) U seq2mset(?B) U seq2mset(?C)
          /\ leq(seq2mset(?A1 @ [?v]), seq2mset(?B))
          /\ leq(seq2mset(?A1 @ [?v]), seq2mset(?C))
          /\ isSorted(?A1 @ [?v]) /\ isSorted(?B) /\ isSorted(?C) */
  while (y != NULL && z != NULL) {
    if (y->val < z->val) {
      p->next = y;
      y = y->next;
    }
    else {
      p->next = z;
      z = z->next;
    }

    p = p->next;
  }

  if (y != NULL)
    p->next = y;
  else
    p->next = z;

  return x;
}
Example #14
0
// function that sorts an array 
void sort(int a[], int size)
{
	// this place we use merge sort
	merge_sort(a, 0, size - 1);
}
Example #15
0
// read and sort output directory
void init_input_files(void) 
{
  DIR *dir;
  struct dirent *ent;
  char output_path[FILE_NAME_SIZE] = "";
  int fret = 0; fret=fret;
  double time;

  sprintf(output_path, "%s/%s", ROOT_DIR, OUTPUT_DIR);

  int isPart;
  int inRange;
  nFiles = 0;

  // count number of part files in directory that fall in time range
  if ((dir = opendir (output_path)) != NULL) {
    while ((ent = readdir (dir)) != NULL) {
      // check if part file (0 if match)
      isPart = (strncmp(ent->d_name, "part", 4) == 0);

      if (isPart == 1) {
        // check if in time range
        fret = sscanf(ent->d_name, "part-%lf.cgns", &time);
        inRange = ((time >= tStart) & (time <= tEnd));
        nFiles += isPart*inRange;
      } else {
        continue;
      }
    }
    closedir (dir);
  } else {
    printf("Output directory does not exist!\n");
    exit(EXIT_FAILURE);
  }

  // store cgns filenames and times within range
  partFiles = (char**) malloc(nFiles * sizeof(char*));
  for (int i = 0; i < nFiles; i ++) {
    partFiles[i] = (char*) malloc(FILE_NAME_SIZE*sizeof(char));
  }
  partFileTime = (double*) malloc(nFiles * sizeof(double));

  int cc = 0;

  if ((dir = opendir (output_path)) != NULL) {
    while ((ent = readdir (dir)) != NULL) {
      isPart = (strncmp(ent->d_name, "part", 4) == 0);

      if (isPart == 1) {
        // check if in time range
        fret = sscanf(ent->d_name, "part-%lf.cgns", &time);
        inRange = ((time >= tStart) & (time <= tEnd));
        
        if (inRange == 1) {
          fret = sscanf(ent->d_name, "%s", partFiles[cc]);
          partFileTime[cc] = time;
          cc++;
        }
      } else {
        continue;
      }
    }
    closedir (dir);
  } else {
    printf("Output directory does not exist!\n");
    exit(EXIT_FAILURE);
  }

  // Sort the resulting array by time
  // create temporary array to sort partFiles by
  fileMap = malloc(nFiles * sizeof(double));
  for (int i = 0; i < nFiles; i++) {
    fileMap[i] = i;
  }

  merge_sort(partFileTime, nFiles, fileMap);
  if (nFiles == 0) {
    printf("Found %d files in range [%lf, %lf]\n", nFiles, tStart, tEnd);
    printf("Quitting...\n");
    exit(EXIT_FAILURE);
  } else {
    printf("Found %d files in range [%lf, %lf]\n", nFiles, tStart, tEnd);
  }
  simTime = (double*) malloc(nFiles * sizeof(double));
}
Example #16
0
void mergesort(T * const array, const int begin, const int end){
  T * helper = new T [end - begin]; 
  merge_sort(array, helper, begin, end, begin);
  delete [] helper;
}
Example #17
0
File: tris.c Project: acekat/PPAR
int main(int argc, char* argv[])
{
	if (argc != 3) {
		fprintf(stderr, "%s\n", usage);
		return 0;
	}

	/* Initialisation */
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	MPI_Comm_size(MPI_COMM_WORLD, &nb_proc);
	
	MPI_Status  status;

	int nb_elem = atoi(argv[1]);	// nombre d'éléments total
	int sort_type = atoi(argv[2]);	// type de l'algorithme de tri

	k = nb_elem / nb_proc;

	int *tab_sort = (int *)malloc(k*sizeof(int));
	int *tab_tmp = (int *)malloc(k*sizeof(int));
	
	if ((tab_tmp == NULL) || (tab_sort == NULL)) {
		fprintf(stderr, "Erreur allocation mémoire du tableau \n");
		MPI_Finalize();
		exit(1);
	}

	int left = my_rank-1;
	int right = my_rank+1;

	// initialise le tableau local
	P0 printf("Initialisation du tableau...");
	switch (sort_type) {
		case 1:	
		case 2: init_rand(tab_tmp, k); break;
		case 3:
		case 4:
		case 5: init_rand(tab_sort, k); break;
	}
	P0 printf(" OK!\n");

	P0 printf("Calcul...\n");

	// début du chronométrage
	double start, end;
	start = MPI_Wtime();
	
	// choix de l'algorithme de tri
	switch (sort_type) {
		case 1: PRAM(tab_tmp, tab_sort); break;
		case 2: PRAM_omp(tab_tmp, tab_sort); break;
		case 3: quick_sort(tab_sort, k); break;
		case 4: quick_sort_omp(tab_sort, k); break;
		case 5: qsort(tab_sort, k, sizeof(int), compare); break;
	}

	// tri pair-impair
	int step;
	for (step = 0; step < nb_proc; step++) {
		if ((my_rank%2) - (step%2) == 0) {
			if (my_rank != nb_proc-1) {
				MPI_Recv(tab_tmp, k, MPI_INT, right, TAG_TAB, MPI_COMM_WORLD, &status);
				merge_sort(tab_sort, tab_tmp);
				MPI_Send(tab_tmp, k, MPI_INT, right, TAG_TAB, MPI_COMM_WORLD);
			}
		}
		else {
			if (my_rank != 0) {
				MPI_Send(tab_sort, k, MPI_INT, left, TAG_TAB, MPI_COMM_WORLD);
				MPI_Recv(tab_sort, k, MPI_INT, left, TAG_TAB, MPI_COMM_WORLD, &status);
			}
		}
	}
	
	// fin du chronométrage
	end = MPI_Wtime();

	print_results(end - start);

	// écriture dans le fichier 	
	if (nb_elem <= NMAX) {
		P0 printf("Ecriture du fichier...");

		MPI_File file; 
		MPI_Offset my_offset;
		char filename[strlen("/Vrac/ppar_cassat_ducamain_sort")+1];
		strcpy(filename, "/Vrac/ppar_cassat_ducamain_sort");	

		my_offset = my_rank * sizeof(int) * k;
		MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_CREATE | MPI_MODE_RDWR, MPI_INFO_NULL, &file);
		MPI_File_write_at(file, my_offset, tab_sort, k, MPI_INT, &status);
		// printf("(%d) a écrit: ", my_rank);
		// print_tab(tab_sort, k);
		
		// attends que tous aient écrit
		MPI_Barrier(MPI_COMM_WORLD);
		
		MPI_File_read_ordered(file, tab_sort, k, MPI_INT, &status);
		MPI_File_close(&file);
		// printf("(%d) a lu: ", my_rank);
		// print_tab(tab_sort, k);

		P0 printf(" OK!\n");
	}

	// Vérification du tri
	P0 printf("Vérification du tri...\n");

	if (!check_sort(tab_sort, k) && (my_rank == 0))
		printf("\tTri correct!\n");

	#ifdef BENCH
	P0 fprintf(stderr, "\t%d\t%d\t%d", sort_type, nb_elem, nb_proc);

	#ifdef _OPENMP
	#pragma omp parallel
	{
		if ((my_rank == 0) && (omp_get_thread_num() == 0))
			fprintf(stderr, "\t%d", omp_get_num_threads());
	}
	#endif
	
	P0 fprintf(stderr, "\n");
	#endif 

	free(tab_sort);
	free(tab_tmp);

	/* Desactivation */
	MPI_Finalize();
	return 0;
}
Example #18
0
/*displays menu, gets input from user and 
selects sorting function according to user choice
and handles program for invalid user inputs*/
int main()         		
{				   
	int choice,size,i,r;
	int *input;

	do{
		printf("\n1.Insertion Sort\n2.Counting Sort\n3.Merge Sort\n4.Randomized Quick Sort\n5.Exit");
		printf("\nEnter your Choice");
		scanf("%d",&choice);
		if(choice<=0 || choice>5){
			printf("Invalid choice: ");
			exit(0);
		}

		if(choice==5)
			exit(0);

		printf("\nEnter size: ");
		scanf("%d",&size);

		if(size<1 || size >1000){
			printf("\nNot in range\n");
			exit(0);
		}

	
		input=malloc(size*sizeof(int)); //allocates input array dynamically

		if(choice==2 && size >20){
			for(i=0;i<size;i++)
				input[i]=rand() %100+0;
		}else if(size <= 20){	
			for(i=0;i<size;i++)
				input[i]=rand() %16+0;
			flag=1;
		}else{
			for(i=0;i<size;i++)
			input[i]=rand();
		}
	
	printf("\nRandomly generated elements are\n");
	for(i=0;i<size;i++)
	printf("%d\t",input[i]);

	if(flag==1){
		//printf("\n\nGraphical representation of data\nInitial array\n");
		//animation(input,0,size);
	}
	
	switch(choice){ //selects sorting algorithm according to user choice 
	case 1:insertion_sort(input,size);
		break;
	case 2:count_sort(input,size);
		break;
	case 3:merge_sort(input,size);
		printf("\n\nsorted elements are:\n ");
			
    		for(i=0;i<size;i++)
         		printf("%d\t",input[i]);
		if(flag==1){
			animation(input,0,size);
			flag=0;
		}
		free(input);
		break;
	case 4:quick_sort(input,0,size-1);
		printf("\n\nsorted elements are: \n");
    		for(i=0;i<size;i++)
       			printf("%d\t",input[i]);
		if(flag==1){
			animation(input,0,size);
			flag=0;
		}
		free(input);
		break;
	
	}
    }
		
	while(choice!=5);

}
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;
}
Example #20
0
// compute forces (gravity)
void compute_forces(void) {
  int l, m;               // iterators
  int i, j, k;            // particle bin indices
  int ii, jj, kk;         // interaction particle bin indices
  float rx, ry, rz, r;    // distance vector components and magnitude
  int n;                  // temporary bin location
  int I, J;               // particle interaction indices

  // set up bin discretization
  float Lx = xe - xs;
  float Ly = ye - ys;
  float Lz = ze - zs;
  int bnx = ceil(Lx / h);
  int bny = ceil(Ly / h);
  int bnz = ceil(Lz / h);
  float bdx = Lx / (float) bnx;
  float bdy = Ly / (float) bny;
  float bdz = Lz / (float) bnz;

  int *pnum = malloc(np * sizeof(int)); // list of particle numbers
  int *pbin = malloc(np * sizeof(int)); // corresponding list of particle bins
  int *bind = malloc(bnx*bny*bnz * sizeof(int));  // starting particle indices

  // loop through particles and put them into bins
  for(l = 0; l < np; l++) {
    pnum[l] = l;
    i = floor((part[l].x - xs) / bdx);
    j = floor((part[l].y - ys) / bdy);
    k = floor((part[l].z - zs) / bdz);

    if(i >= bnx) i = bnx - 1;
    if(i < 0) i = 0;
    if(j >= bny) j = bny - 1;
    if(j < 0) j = 0;
    if(k >= bnz) k = bnz - 1;
    if(k < 0) k = 0;

    pbin[l] = i + j*bnx + k*bnx*bny;
  }

  // sort by pbin
  merge_sort(pbin, np, pnum);

  // set up starting index list
  for(l = 0; l < bnx*bny*bnz; l++) {
    bind[l] = -1;
  }
  // determine starting index for each bin
  bind[pbin[0]] = 0;
  for(l = 1; l < np; l++) {
    if(pbin[l] > pbin[l-1]) { // if the bin number changes
      bind[pbin[l]] = l;      // store the bin number
    }
  }

  // interact particles in this and surrounding bins
  for(l = 0; l < np; l++) { // visit all particles
    // determine bin coordinates
    k = pbin[l] / (bnx*bny);
    j = (pbin[l] - k*bnx*bny) / bnx;
    i = pbin[l] - j*bnx - k*bnx*bny;
    I = pnum[l];  // this particle number

    // set sum of forces equal to zero
    part[I].Fx = 0.;
    part[I].Fy = 0.;
    part[I].Fz = 0.;

    // visit all sourrounding bins
    for(kk = k-1; kk <= k+1; kk++) {
      for(jj = j-1; jj <= j+1; jj++) {
        for(ii = i-1; ii <= i+1; ii++) {
          // make sure neighbors exist
          if(  ii >= 0 && ii < bnx
            && jj >= 0 && jj < bny
            && kk >= 0 && kk < bnz) {

            n = ii + jj*bnx + kk*bnx*bny;   // cell number

            m = bind[n];
            if(m > -1) {
              while(pbin[m] == pbin[bind[n]]) {
                J = pnum[m];  // other particle number

                // do not interact with self
                if(I != J) {
                  // separation vector
                  rx = part[J].x - part[I].x;
                  ry = part[J].y - part[I].y;
                  rz = part[J].z - part[I].z;
                  // modulus of separation vector
                  r  = sqrt(rx*rx + ry*ry + rz*rz);

                  // if not contacting, compute force due to gravity
                  if(r > (part[I].r + part[J].r)) {
                    part[I].Fx += (rx / r) * G * part[I].m * part[J].m / (r*r);
                    part[I].Fy += (ry / r) * G * part[I].m * part[J].m / (r*r);
                    part[I].Fz += (rz / r) * G * part[I].m * part[J].m / (r*r);
                  } else {  // if contacting, apply spring force to separate
                    part[I].Fx -= (rx / r) * part[I].E * fabs(part[I].r - r);
                    part[I].Fy -= (ry / r) * part[I].E * fabs(part[I].r - r);
                    part[I].Fz -= (rz / r) * part[I].E * fabs(part[I].r - r);
                  }
                }
                m++;  // move to the next particle in the bin

                // exit loop if the next m is one too far
                if(m == np) {
                  break;
                }
              }
            }
          }
        }
      }
    }
  }

  free(pnum);
  free(pbin);
  free(bind);
}
Example #21
0
void
fsort(struct filelist *filelist, int nfiles, FILE *outfp, struct field *ftbl)
{
	RECHEADER **keylist;
	RECHEADER **keypos, **keyp;
	RECHEADER *buffer;
	size_t bufsize = DEFBUFSIZE;
	u_char *bufend;
	int mfct = 0;
	int c, nelem;
	get_func_t get;
	RECHEADER *crec;
	RECHEADER *nbuffer;
	FILE *fp, *tmp_fp;
	int file_no;
	int max_recs = DEBUG('m') ? 16 : MAXNUM;

	buffer = allocrec(NULL, bufsize);
	bufend = (u_char *)buffer + bufsize;
	/* Allocate double length keymap for radix_sort */
	keylist = malloc(2 * max_recs * sizeof(*keylist));
	if (buffer == NULL || keylist == NULL)
		err(2, "failed to malloc initial buffer or keylist");

	if (SINGL_FLD)
		/* Key and data are one! */
		get = makeline;
	else
		/* Key (merged key fields) added before data */
		get = makekey;

	file_no = 0;
	fp = fopen(filelist->names[0], "r");
	if (fp == NULL)
		err(2, "%s", filelist->names[0]);

	/* Loop through reads of chunk of input files that get sorted
	 * and then merged together. */
	for (;;) {
		keypos = keylist;
		nelem = 0;
		crec = buffer;
		makeline_copydown(crec);

		/* Loop reading records */
		for (;;) {
			c = get(fp, crec, bufend, ftbl);
			/* 'c' is 0, EOF or BUFFEND */
			if (c == 0) {
				/* Save start of key in input buffer */
				*keypos++ = crec;
				if (++nelem == max_recs) {
					c = BUFFEND;
					break;
				}
				crec = (RECHEADER *)(crec->data + SALIGN(crec->length));
				continue;
			}
			if (c == EOF) {
				/* try next file */
				if (++file_no >= nfiles)
					/* no more files */
					break;
				fp = fopen(filelist->names[file_no], "r");
				if (fp == NULL)
					err(2, "%s", filelist->names[file_no]);
				continue;
			}
			if (nelem >= max_recs
			    || (bufsize >= MAXBUFSIZE && nelem > 8))
				/* Need to sort and save this lot of data */
				break;

			/* c == BUFFEND, and we can process more data */
			/* Allocate a larger buffer for this lot of data */
			bufsize *= 2;
			nbuffer = allocrec(buffer, bufsize);
			if (!nbuffer) {
				err(2, "failed to realloc buffer to %zu bytes",
					bufsize);
			}

			/* patch up keylist[] */
			for (keyp = &keypos[-1]; keyp >= keylist; keyp--)
				*keyp = nbuffer + (*keyp - buffer);

			crec = nbuffer + (crec - buffer);
			buffer = nbuffer;
			bufend = (u_char *)buffer + bufsize;
		}

		/* Sort this set of records */
		radix_sort(keylist, keylist + max_recs, nelem);

		if (c == EOF && mfct == 0) {
			/* all the data is (sorted) in the buffer */
			append(keylist, nelem, outfp,
			    DEBUG('k') ? putkeydump : putline);
			break;
		}

		/* Save current data to a temporary file for a later merge */
		if (nelem != 0) {
			tmp_fp = ftmp();
			append(keylist, nelem, tmp_fp, putrec);
			save_for_merge(tmp_fp, geteasy, ftbl);
		}
		mfct = 1;

		if (c == EOF) {
			/* merge to output file */
			merge_sort(outfp, 
			    DEBUG('k') ? putkeydump : putline, ftbl);
			break;
		}
	}

	free(keylist);
	keylist = NULL;
	free(buffer);
	buffer = NULL;
}
// Reads file and allocates shared memory
int merge_sort_init(int argc, char *argv[]) {
  if( argc == 2) {         	// If the filename argument is given
    printf("\nSorting file: %s\n",argv[1]);
    int count = 0;
    
    int *array;
    array = (int *) malloc(1*sizeof(int));

    FILE *fp;
    fp = fopen(argv[1], "r");

    if (fp == NULL) {     				// Failed file open
      printf("Error opening the file\n");
      return 1;

    } else {            				// Successful file open
      while(fscanf(fp, "%d", &array[count]) != EOF) {
        count++;
        array = (int *) realloc(array,(count + 1) * (sizeof(int)));
      }
      fclose(fp);
    }

    printf("%d elements read\n\n", count);		// If no integers are in the file
    if (count == 0) {
        free(array);
    	return 0;
    }

    int shmid;						// Allocate Shared Memory
    int *shmptr;
    shmid = shmget(IPC_PRIVATE, count *(sizeof(int)),0600);
    if (shmid < 0) {					
        printf("shmget error");
	return 1;
    }

    shmptr = shmat(shmid, 0, 0);			//  Shared Memory pointer
    if (shmptr == (void *)-1) {
	printf("shmat error");
	return 1;
    }
    int i;						// Copy local array to Shared Memory
    for (i = 0; i < count; i++) {
	shmptr[i] = array[i];
    }
    
    free(array);

    
    printf("Input Numbers:\n");
    int k;
    for (k = 0; k < count; k++) {       	 	// Read numbers before sort
      printf("%d ", shmptr[k]);
    }
    printf("\n\n");

    
    if (merge_sort(shmptr, 0, count - 1) == 1) {     	// Call recursive merge_sort
    	printf("Merge sort error");
	return 1;
    }

    printf("Sorted Numbers:\n");
    for (k = 0; k < count; k++) {      		     	// Read numbers after sort
      printf("%d ", shmptr[k]);
    }
    printf("\n\n");

    shmdt(&shmid);
    
  } else {               			    	// If the filename argument is not given
    printf("This program requires one filename argument\n");
    return 1;
  }
  
  return 0;
}
Example #23
0
int main(int argc, char *argv[]) {
    plist_info            plist;
    char                  filename_root[256];
    char                  filename_log[256];
    char                  filename_number[256];
    char                  filename_in_halos[256];
    char                  filename_out_groups[256];
    char                  filename_out_groups_A[256];
    char                  filename_out_groups_B[256];
    char                  filename_out_groups_C[256];
    char                  filename_out_subgroups[256];
    char                  filename_out_subgroups_A[256];
    char                  filename_out_subgroups_B[256];
    char                  filename_out_hierarchy[256];
    char                  filename_out_hierarchy_A[256];
    char                  filename_out_hierarchy_B[256];
    char                  filename_out_particles[256];
    char                  i_match_txt[5];
    int                   n_groups_AHF;
    int                   n_groups;
    int                   n_subgroups;
    int                   n_subgroups_matched;
    int                   n_subgroups_group;
    size_t                n_particles;
    size_t                n_particles_in_groups;
    size_t                n_particles_in_subgroups;
    size_t                n_particles_AHF_not_used;
    int                   n_particles_temp;
    int *                 n_p_1 = NULL;
    int                   flag_continue;
    int                   flag_long_ids;
    int                   i_match;
    int                   match_id_next;
    int *                 match_id         = NULL;
    int *                 match_id_initial = NULL;
    FILE *                fp               = NULL;
    FILE *                fp_in_halos      = NULL;
    FILE *                fp_out           = NULL;
    int                   n_match;
    int *                 id_2                   = NULL;
    size_t *              particle_ids_AHF       = NULL;
    size_t *              particle_ids_AHF_index = NULL;
    size_t                id_largest;
    int                   id_byte_size;
    size_t *              group_particles = NULL;
    int                   group_id;
    int                   subgroup_id;
    int                   i_group;
    int                   j_group;
    int                   k_group;
    size_t                n_particles_AHF;
    int *                 subgroup_size   = NULL;
    int *                 hierarchy_level = NULL;
    int *                 hierarchy_match = NULL;
    int                   subgroup_size_max;
    int *                 subgroup_size_list       = NULL;
    int *                 subgroup_index_list      = NULL;
    size_t *              subgroup_size_list_index = NULL;
    int *                 group_offsets            = NULL;
    size_t                group_index;
    int *                 group_size        = NULL;
    int *                 group_size_AHF    = NULL;
    int *                 group_offsets_AHF = NULL;
    int                   max_subgroup_size;
    int                   i_subgroup;
    int                   j_subgroup;
    int                   n_subgroups_group_max;
    size_t *              group_size_index = NULL;
    size_t *              match_id_index   = NULL;
    size_t                subgroup_index;
    int                   group_offset;
    int                   subgroup_offset;
    int                   group_count;
    size_t *              group_particles_index = NULL;
    size_t *              subgroup_particles    = NULL;
    int *                 particle_group        = NULL;
    size_t *              particle_group_index  = NULL;
    size_t                i_particle;
    size_t                j_particle;
    size_t                k_particle;
    int                   i_file;
    int                   i_file_start;
    int                   i_file_stop;
    size_t *              match_index = NULL;
    int                   flag_match_subgroups;
    FILE *                fp_log             = NULL;
    FILE *                fp_in              = NULL;
    FILE *                fp_out_particles   = NULL;
    FILE *                fp_out_groups      = NULL;
    FILE *                fp_out_groups_A    = NULL;
    FILE *                fp_out_groups_B    = NULL;
    FILE *                fp_out_groups_C    = NULL;
    FILE *                fp_out_subgroups_A = NULL;
    FILE *                fp_out_subgroups_B = NULL;
    FILE *                fp_out_hierarchy_A = NULL;
    FILE *                fp_out_hierarchy_B = NULL;
    FILE *                fp_test            = NULL;
    int                   substructure_level;
    int                   substructure_level_max;
    halo_properties_info *properties      = NULL;
    void *                particle_buffer = NULL;
    int                   flag_found;

    SID_Init(&argc, &argv, NULL);

    strcpy(filename_root, argv[1]);
    i_file_start = atoi(argv[2]);
    i_file_stop  = atoi(argv[3]);

    SID_log("Converting files #%d->#%d from AHF to subfind format...", SID_LOG_OPEN | SID_LOG_TIMER, i_file_start, i_file_stop);

    sprintf(filename_log, "%s_%dto%d.convert_AHF_log", filename_root, i_file_start, i_file_stop);

    // Loop over all files
    for(i_file = i_file_start; i_file <= i_file_stop; i_file++) {
        SID_log("Processing file #%d...", SID_LOG_OPEN | SID_LOG_TIMER, i_file);

        // Read catalogs
        if(i_file < 10)
            sprintf(filename_number, "00%1d", i_file);
        else if(i_file < 100)
            sprintf(filename_number, "0%2d", i_file);
        else
            sprintf(filename_number, "%3d", i_file);

        // Read AHF group file
        init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY);
        read_groups_AHF(filename_root, i_file, READ_GROUPS_ALL, &plist, filename_number);
        n_groups_AHF = ((int *)ADaPS_fetch(plist.data, "n_groups_%s", filename_number))[0];

        n_groups                 = 0;
        n_subgroups              = 0;
        n_subgroups_matched      = 0;
        n_subgroups_group        = 0;
        n_particles              = 0;
        n_particles_in_groups    = 0;
        n_particles_in_subgroups = 0;
        n_particles_AHF_not_used = 0;
        n_subgroups_group_max    = 0;

        if(n_groups_AHF > 0) {
            n_particles_AHF   = (size_t)((size_t *)ADaPS_fetch(plist.data, "n_particles_%s", filename_number))[0];
            group_size_AHF    = (int *)ADaPS_fetch(plist.data, "n_particles_group_%s", filename_number);
            group_offsets_AHF = (int *)ADaPS_fetch(plist.data, "particle_offset_group_%s", filename_number);
            particle_ids_AHF  = (size_t *)ADaPS_fetch(plist.data, "particle_ids_%s", filename_number);

            // Find largest id so we know what size to write the ids with
            for(i_particle = 0, id_largest = 0; i_particle < n_particles_AHF; i_particle++)
                id_largest = GBP_MAX(id_largest, particle_ids_AHF[i_particle]);
            if(id_largest > INT_MAX) {
                flag_long_ids = GBP_TRUE;
                id_byte_size  = sizeof(size_t);
            } else {
                flag_long_ids = GBP_FALSE;
                id_byte_size  = sizeof(int);
            }

            // Match AHF groups against themselves to find substructure
            match_halos(&plist, NULL, i_file, NULL, 0, &plist, NULL, i_file, NULL, 0, "substructure", MATCH_SUBSTRUCTURE, MATCH_SCORE_RANK_INDEX);
            match_id_initial = (int *)ADaPS_fetch(plist.data, "match_substructure");
            hierarchy_match  = match_id_initial; // Fore readability

            // Assign sub-...-sub-structures to parent (ie. top-level) halos
            SID_log("Assigning substructures to groups...", SID_LOG_OPEN);
            group_size      = (int *)SID_malloc(sizeof(int) * n_groups_AHF);
            subgroup_size   = (int *)SID_malloc(sizeof(int) * n_groups_AHF);
            hierarchy_level = (int *)SID_malloc(sizeof(int) * n_groups_AHF);
            particle_group  = (int *)SID_malloc(sizeof(int) * n_particles_AHF);
            for(i_group = 0, i_particle = 0; i_group < n_groups_AHF; i_group++) {
                group_size[i_group]    = 0;
                subgroup_size[i_group] = 0;
                for(j_particle = 0; j_particle < group_size_AHF[i_group]; i_particle++, j_particle++)
                    particle_group[i_particle] = i_group;
            }
            match_id = (int *)SID_malloc(sizeof(int) * n_groups_AHF);
            for(i_group = 0, substructure_level_max = 0; i_group < n_groups_AHF; i_group++) {
                substructure_level = 0;
                match_id_next      = match_id_initial[i_group];
                match_id[i_group]  = match_id_next;
                while(match_id_next >= 0) {
                    substructure_level++;
                    match_id[i_group] = match_id_next; // Tie subgroups to their top-level group
                    match_id_next     = match_id_initial[match_id_next];
                }
                if(match_id[i_group] < 0)
                    match_id[i_group] = i_group; // Unmatched halos should be matched to themselves
                hierarchy_level[i_group] = substructure_level;
                substructure_level_max   = GBP_MAX(substructure_level, substructure_level_max);
            }
            // needed? ADaPS_store(&(plist.data),(void *)(match_id),"match_substructure",ADaPS_DEFAULT);
            SID_log("Done.", SID_LOG_CLOSE);

            // Make sure the deepest substructures are given particle ownership
            SID_log("Assigning particles to subgroups...", SID_LOG_OPEN);
            merge_sort(
                (void *)particle_ids_AHF, (size_t)n_particles_AHF, &particle_ids_AHF_index, SID_SIZE_T, SORT_COMPUTE_INDEX, SORT_COMPUTE_NOT_INPLACE);
            for(i_particle = 0, n_particles_AHF_not_used = 0; i_particle < n_particles_AHF; i_particle += k_particle) {
                // Count the number of times this particle id is used
                j_particle = i_particle;
                while(particle_ids_AHF[particle_ids_AHF_index[j_particle]] == particle_ids_AHF[particle_ids_AHF_index[i_particle]] &&
                      j_particle < (n_particles_AHF - 2))
                    j_particle++;
                if(particle_ids_AHF[particle_ids_AHF_index[j_particle]] == particle_ids_AHF[particle_ids_AHF_index[i_particle]])
                    j_particle++;
                k_particle = j_particle - i_particle;
                // Find the deepest substructure using this particle id...
                i_group = particle_group[particle_ids_AHF_index[i_particle]];
                for(j_particle = 1; j_particle < k_particle; j_particle++) {
                    j_group = particle_group[particle_ids_AHF_index[i_particle + j_particle]];
                    if(group_size_AHF[j_group] < group_size_AHF[i_group])
                        i_group = j_group;
                }
                // ... and set particle's group to a dummy value if this particle instance is not from the deepest group
                for(j_particle = 0, flag_found = GBP_FALSE; j_particle < k_particle; j_particle++) {
                    if(particle_group[particle_ids_AHF_index[i_particle + j_particle]] != i_group || flag_found) {
                        particle_group[particle_ids_AHF_index[i_particle + j_particle]] = -1;
                        n_particles_AHF_not_used++;
                    } else
                        flag_found = GBP_TRUE;
                }
            }
            SID_free((void **)&particle_ids_AHF_index);
            SID_log("Done.", SID_LOG_CLOSE);

            // Generate subgroup_size array
            for(i_group = 0; i_group < n_groups_AHF; i_group++)
                subgroup_size[i_group] = 0;
            for(i_particle = 0; i_particle < n_particles_AHF; i_particle++) {
                i_group = particle_group[i_particle];
                if(i_group >= 0)
                    subgroup_size[i_group]++;
            }

            // Get rid of groups that are too small
            for(i_particle = 0; i_particle < n_particles_AHF; i_particle++) {
                i_group = particle_group[i_particle];
                if(i_group >= 0) {
                    if(subgroup_size[i_group] < 20) {
                        n_particles_AHF_not_used++;
                        particle_group[i_particle] = -1;
                    }
                }
            }

            // Regenerate subgroup_size array
            for(i_group = 0; i_group < n_groups_AHF; i_group++)
                subgroup_size[i_group] = 0;
            for(i_particle = 0; i_particle < n_particles_AHF; i_particle++) {
                i_group = particle_group[i_particle];
                if(i_group >= 0)
                    subgroup_size[i_group]++;
            }

            // Find the largest subgroup's size
            for(i_group = 0, n_subgroups = 0, subgroup_size_max = 0; i_group < n_groups_AHF; i_group++)
                subgroup_size_max = GBP_MAX(subgroup_size[i_group], subgroup_size_max);

            // Generate group_size array
            for(i_group = 0; i_group < n_groups_AHF; i_group++)
                group_size[match_id[i_group]] += subgroup_size[i_group]; // update group size

            // Sort groups in order of size
            merge_sort((void *)group_size, (size_t)n_groups_AHF, &group_size_index, SID_INT, SORT_COMPUTE_INDEX, SORT_COMPUTE_NOT_INPLACE);
            merge_sort((void *)match_id, (size_t)n_groups_AHF, &match_id_index, SID_INT, SORT_COMPUTE_INDEX, SORT_COMPUTE_NOT_INPLACE);

            // Count groups, subgroups, etc.
            SID_log("Counting groups & subgroups...", SID_LOG_OPEN);
            for(i_group = 0, n_groups = 0, n_subgroups = 0; i_group < n_groups_AHF; i_group++) {
                group_index = group_size_index[n_groups_AHF - i_group - 1];

                // Find start of subgroup list for this group
                j_group = find_index_int(match_id, group_index, n_groups_AHF, match_id_index);
                while(group_index > match_id[match_id_index[j_group]] && j_group < (n_groups_AHF - 2))
                    j_group++;
                if(group_index > match_id[match_id_index[j_group]])
                    j_group++;

                // Count subgroups
                n_subgroups_group = 0;
                while(match_id[match_id_index[j_group]] == group_index && j_group < (n_groups_AHF - 2)) {
                    if(subgroup_size[match_id_index[j_group]] > 0)
                        n_subgroups_group++;
                    j_group++;
                }
                if(match_id[match_id_index[j_group]] == group_index) {
                    if(subgroup_size[match_id_index[j_group]] > 0)
                        n_subgroups_group++;
                    j_group++;
                }
                n_subgroups += n_subgroups_group;

                // Largest number of subgroups
                n_subgroups_group_max = GBP_MAX(n_subgroups_group_max, n_subgroups_group);

                // Count groups
                if(n_subgroups_group > 0)
                    n_groups++;
            }
            SID_log("Done.", SID_LOG_CLOSE);
        }

        // Find largest subgroup and count the number of particles in groups
        for(i_group = 0, max_subgroup_size = 0, n_particles_in_groups = 0; i_group < n_groups_AHF; i_group++) {
            max_subgroup_size = GBP_MAX(max_subgroup_size, subgroup_size[i_group]);
            if(subgroup_size[i_group] > 0)
                n_particles_in_groups += (size_t)subgroup_size[i_group];
        }

        // Write some statistics
        SID_log("Substructure statistics:", SID_LOG_OPEN);
        SID_log("Number of groups                 =%d", SID_LOG_COMMENT, n_groups);
        SID_log("Number of subgroups              =%d", SID_LOG_COMMENT, n_subgroups);
        SID_log("Max number of subgroups per group=%d", SID_LOG_COMMENT, n_subgroups_group_max);
        SID_log("Largest subgroup                 =%d particles", SID_LOG_COMMENT, subgroup_size_max);
        SID_log("Depth of substructure heirarchy  =%d levels", SID_LOG_COMMENT, substructure_level_max);
        SID_log("Number of AHF particles used     =%lld", SID_LOG_COMMENT, n_particles_in_groups);
        SID_log("Number of AHF particles NOT used =%lld", SID_LOG_COMMENT, n_particles_AHF_not_used);
        SID_log("", SID_LOG_CLOSE | SID_LOG_NOPRINT);

        // Open files
        SID_set_verbosity(SID_SET_VERBOSITY_RELATIVE, 0);
        SID_log("Writing %d groups, %d subgroups and %lld particles to files...",
                SID_LOG_OPEN | SID_LOG_TIMER,
                n_groups,
                n_subgroups,
                n_particles_in_groups);
        sprintf(filename_out_groups, "%s_%s.catalog_groups", filename_root, filename_number);
        sprintf(filename_out_groups_A, "%s_%s.catalog_groups_A", filename_root, filename_number);
        sprintf(filename_out_groups_B, "%s_%s.catalog_groups_B", filename_root, filename_number);
        sprintf(filename_out_groups_C, "%s_%s.catalog_groups_C", filename_root, filename_number);
        sprintf(filename_out_subgroups, "%s_%s.catalog_subgroups", filename_root, filename_number);
        sprintf(filename_out_subgroups_A, "%s_%s.catalog_subgroups_A", filename_root, filename_number);
        sprintf(filename_out_subgroups_B, "%s_%s.catalog_subgroups_B", filename_root, filename_number);
        sprintf(filename_out_hierarchy, "%s_%s.catalog_hierarchy", filename_root, filename_number);
        sprintf(filename_out_hierarchy_A, "%s_%s.catalog_hierarchy_A", filename_root, filename_number);
        sprintf(filename_out_hierarchy_B, "%s_%s.catalog_hierarchy_B", filename_root, filename_number);
        sprintf(filename_out_particles, "%s_%s.catalog_particles", filename_root, filename_number);
        fp_out_groups_A    = fopen(filename_out_groups_A, "w");
        fp_out_groups_B    = fopen(filename_out_groups_B, "w");
        fp_out_groups_C    = fopen(filename_out_groups_C, "w");
        fp_out_subgroups_A = fopen(filename_out_subgroups_A, "w");
        fp_out_subgroups_B = fopen(filename_out_subgroups_B, "w");
        fp_out_hierarchy_A = fopen(filename_out_hierarchy_A, "w");
        fp_out_hierarchy_B = fopen(filename_out_hierarchy_B, "w");
        fp_out_particles   = fopen(filename_out_particles, "w");

        // Write headers
        fwrite(&n_groups, sizeof(int), 1, fp_out_groups_A);
        fwrite(&n_subgroups, sizeof(int), 1, fp_out_subgroups_A);
        fwrite(&n_subgroups, sizeof(int), 1, fp_out_hierarchy_A);
        fwrite(&id_byte_size, sizeof(int), 1, fp_out_particles);
        switch(flag_long_ids) {
            case GBP_TRUE:
                fwrite(&n_particles_in_groups, sizeof(size_t), 1, fp_out_particles);
                break;
            default:
                n_particles_temp = (int)n_particles_in_groups;
                fwrite(&n_particles_temp, sizeof(int), 1, fp_out_particles);
                break;
        }

        // Write files; group and subgroup files in parts (to be concatinated together later)
        subgroup_size_list  = (int *)SID_malloc(sizeof(int) * n_subgroups_group_max);
        subgroup_index_list = (int *)SID_malloc(sizeof(int) * n_subgroups_group_max);
        particle_buffer     = (void *)SID_malloc(id_byte_size * subgroup_size_max);
        subgroup_offset     = 0;
        group_offset        = 0;

        for(i_group = n_groups_AHF - 1; i_group >= n_groups_AHF - n_groups; i_group--) {
            group_index = group_size_index[i_group];

            // Find start of subgroup list for this group
            i_subgroup = find_index_int(match_id, group_index, n_groups_AHF, match_id_index);
            while(group_index > match_id[match_id_index[i_subgroup]] && i_subgroup < (n_groups_AHF - 2))
                i_subgroup++;
            if(group_index > match_id[match_id_index[i_subgroup]])
                i_subgroup++;

            // Create a list of subgroups for this group and sort it by size
            n_subgroups_group = 0;
            subgroup_index    = match_id_index[i_subgroup];
            while(match_id[subgroup_index] == group_index && i_subgroup < (n_groups_AHF - 2)) {
                if(subgroup_size[subgroup_index] > 0) {
                    subgroup_size_list[n_subgroups_group]  = subgroup_size[subgroup_index];
                    subgroup_index_list[n_subgroups_group] = (int)subgroup_index;
                    n_subgroups_group++;
                }
                i_subgroup++;
                subgroup_index = match_id_index[i_subgroup];
            }
            if(match_id[subgroup_index] == group_index) {
                if(subgroup_size[subgroup_index] > 0) {
                    subgroup_size_list[n_subgroups_group]  = subgroup_size[subgroup_index];
                    subgroup_index_list[n_subgroups_group] = (int)subgroup_index;
                    n_subgroups_group++;
                }
                i_subgroup++;
                subgroup_index = match_id_index[i_subgroup];
            }
            merge_sort((void *)subgroup_size_list,
                       (size_t)n_subgroups_group,
                       &subgroup_size_list_index,
                       SID_INT,
                       SORT_COMPUTE_INDEX,
                       SORT_COMPUTE_NOT_INPLACE);

            // Perform writes for subgroups and particle lists
            for(i_subgroup = 0, i_particle = 0; i_subgroup < n_subgroups_group; i_subgroup++) {
                j_subgroup = subgroup_index_list[subgroup_size_list_index[n_subgroups_group - i_subgroup - 1]];
                // ... subgroups ...
                fwrite(&(subgroup_size[j_subgroup]), sizeof(int), 1, fp_out_subgroups_A);
                fwrite(&(subgroup_offset), sizeof(int), 1, fp_out_subgroups_B);
                fwrite(&(hierarchy_match[j_subgroup]), sizeof(int), 1, fp_out_hierarchy_A);
                fwrite(&(hierarchy_level[j_subgroup]), sizeof(int), 1, fp_out_hierarchy_B);
                subgroup_offset += subgroup_size[j_subgroup];
                // ... and particles
                for(j_particle = group_offsets_AHF[j_subgroup], k_particle = 0, i_particle = 0; k_particle < group_size_AHF[j_subgroup];
                    j_particle++, k_particle++) {
                    if(particle_group[j_particle] == j_subgroup) {
                        switch(flag_long_ids) {
                            case GBP_TRUE:
                                ((size_t *)particle_buffer)[i_particle++] = (size_t)(particle_ids_AHF[j_particle]);
                                break;
                            default:
                                ((int *)particle_buffer)[i_particle++] = (int)(particle_ids_AHF[j_particle]);
                                break;
                        }
                    }
                }
                if(i_particle == subgroup_size[j_subgroup])
                    fwrite(particle_buffer, id_byte_size, i_particle, fp_out_particles);
                else
                    SID_exit_error("Subgroup size mismatch!", SID_ERROR_LOGIC);
            }

            SID_free((void **)&subgroup_size_list_index);

            // Perform writes for groups
            fwrite(&(group_size[group_index]), sizeof(int), 1, fp_out_groups_A);
            fwrite(&group_offset, sizeof(int), 1, fp_out_groups_B);
            fwrite(&n_subgroups_group, sizeof(int), 1, fp_out_groups_C);
            group_offset += group_size[group_index];
        }
        SID_free((void **)&subgroup_size_list);
        SID_free((void **)&subgroup_index_list);
        SID_free((void **)&particle_buffer);

        fclose(fp_out_groups_A);
        fclose(fp_out_groups_B);
        fclose(fp_out_groups_C);
        fclose(fp_out_subgroups_A);
        fclose(fp_out_subgroups_B);
        fclose(fp_out_hierarchy_A);
        fclose(fp_out_hierarchy_B);
        fclose(fp_out_particles);

        // Concatinate group and subgroup temp files into final files
        SID_cat_files(filename_out_groups, SID_CAT_CLEAN, 3, filename_out_groups_A, filename_out_groups_B, filename_out_groups_C);

        SID_cat_files(filename_out_subgroups, SID_CAT_CLEAN, 2, filename_out_subgroups_A, filename_out_subgroups_B);

        SID_cat_files(filename_out_hierarchy, SID_CAT_CLEAN, 2, filename_out_hierarchy_A, filename_out_hierarchy_B);

        // Clean-up
        SID_free((void **)&subgroup_size);
        SID_free((void **)&hierarchy_level);
        SID_free((void **)&group_size);
        SID_free((void **)&group_size_index);
        SID_free((void **)&match_id_index);
        free_plist(&plist);
        SID_set_verbosity(SID_SET_VERBOSITY_DEFAULT);
        SID_log("Done.", SID_LOG_CLOSE);

        // Write log file
        SID_log("Writing to log file...", SID_LOG_OPEN);
        // Write a header for the log file
        if(i_file == i_file_start) {
            fp_log = fopen(filename_log, "w");
            fprintf(fp_log, "# (1):  filenumber\n");
            fprintf(fp_log, "# (2):  n_groups_AHF\n");
            fprintf(fp_log, "# (3):  n_particles_AHF\n");
            fprintf(fp_log, "# (4):  n_groups\n");
            fprintf(fp_log, "# (5):  n_subgroups\n");
            fprintf(fp_log, "# (6):  max number of subgroups per group\n");
            fprintf(fp_log, "# (7):  largest subgroup\n");
            fprintf(fp_log, "# (8):  depth of substructure heirarchy\n");
            fprintf(fp_log, "# (9):  number of AHF particles used\n");
            fprintf(fp_log, "# (10): number of AHF particles NOT used\n");
        } else
            fp_log = fopen(filename_log, "a");
        fprintf(fp_log,
                "%4d %9d %12zd %9d %9d %9d %9d %9d %12zd %12zd\n",
                i_file,
                n_groups_AHF,
                n_particles_AHF,
                n_groups,
                n_subgroups,
                n_subgroups_group_max,
                subgroup_size_max,
                substructure_level_max,
                n_particles_in_groups,
                n_particles_AHF_not_used);
        fclose(fp_log);

        SID_log("Done.", SID_LOG_CLOSE);

        SID_log("Done.", SID_LOG_CLOSE);
    }

    SID_log("Done.", SID_LOG_CLOSE);
    SID_Finalize();
}
Example #24
0
void
mergeSort (int data[], int size)
{
  merge_sort (data, 0, size - 1);
}
Example #25
0
int main()
{
    merge_sort(A, 0, 6);
    dump(A, 7);
//    dump(C, 7);
}
Example #26
0
void read_matches(char    *filename_in_dir,
                  int      i_read_in,
                  int      j_read_in,
                  int      n_halos_max,
                  int      mode,
                  int     *n_groups_i,
                  int     *n_groups_j,
                  int     *n_particles_i_in,
                  int     *n_particles_j_in,
                  int     *n_sub_group_i_in,
                  int     *n_sub_group_j_in,
                  int     *match_ids,
                  float   *match_score,
                  size_t  *match_index,
                  char    *match_flag_two_way,
                  int      flag_reject_bad_matches){
   char   group_text_prefix[5];
   char   filename_in[MAX_FILENAME_LENGTH];
   SID_fp fp_in;
   int    k_read;
   int    l_read;
   int    n_search;
   int    n_matches;
   size_t offset;
   int    flag_continue;
   int    i_read_file;
   int    j_read_file;
   int    n_groups_file;
   int    n_groups_file_1;
   int    n_groups_file_2;
   int    n_groups;
   int    n_groups_i_file;
   int    n_groups_j_file;
   int   *n_sub_group_i;
   int   *n_sub_group_j;
   int    flag_alloc_n_sub_i=FALSE;
   int    flag_alloc_n_sub_j=FALSE;
   
   if(i_read_in==j_read_in)
     SID_trap_error("i_read=j_read in read_matches",ERROR_LOGIC);

   switch(mode){
      case MATCH_SUBGROUPS:
      sprintf(group_text_prefix,"sub");
      break;
      case MATCH_GROUPS:
      sprintf(group_text_prefix,"");
      // We need n_subgroups arrays for removal of bad groups
      //    if they have not been passed to us.
      if(n_sub_group_i_in==NULL){
         flag_alloc_n_sub_i=TRUE;
         n_sub_group_i     =(int *)SID_malloc(sizeof(int)*n_halos_max);
      }
      else
         n_sub_group_i=n_sub_group_i_in;
      if(n_sub_group_j_in==NULL){
         flag_alloc_n_sub_j=TRUE;
         n_sub_group_j     =(int *)SID_malloc(sizeof(int)*n_halos_max);
      }
      else
         n_sub_group_j=n_sub_group_j_in;
      break;
   }

   // Since we need the particle counts for the goodness of match criterion,
   //   create temporary arrays in case we weren't passed an array for them.
   int *n_particles_i=n_particles_i_in;
   int *n_particles_j=n_particles_j_in;
   // 1) We always need n_particles_i
   int  flag_alloc_n_particles_i=FALSE;
   int  flag_alloc_n_particles_j=FALSE;
   if(n_particles_i==NULL)
      flag_alloc_n_particles_i=TRUE;
   if(n_particles_j==NULL)
      flag_alloc_n_particles_j=TRUE;
   // 2) We need n_particles_j if doing 2-way checks
   if(match_flag_two_way!=NULL && n_particles_j==NULL)
      flag_alloc_n_particles_j=TRUE;

   // Read the needed info from the header file
   int  i_read;
   int  i_read_start;
   int  i_read_stop;
   int  n_search_total;
   int  n_files;
   int  n_groups_in;
   int  counter=0;
   char filename_in_name[256];
   strcpy(filename_in_name,filename_in_dir);
   strip_path(filename_in_name);
   sprintf(filename_in,"%s/%sgroup_matches_header.dat",filename_in_dir,group_text_prefix);
   SID_fopen(filename_in,"r",&fp_in);
   SID_fread(&i_read_start,  sizeof(int),1,&fp_in);
   SID_fread(&i_read_stop,   sizeof(int),1,&fp_in);
   SID_fread(&n_search_total,sizeof(int),1,&fp_in);
   SID_fread(&n_files,       sizeof(int),1,&fp_in);
   for(i_read=i_read_stop;i_read>=i_read_start && counter<2;i_read--){
      SID_fread(&i_read_file, sizeof(int),1,&fp_in);
      if(i_read_file==i_read_in){
         SID_fread(n_groups_i,sizeof(int),1,&fp_in);
         if((*n_groups_i)>0){
            // Create a temporary array for n_particles_i if we were not passed one
            if(flag_alloc_n_particles_i)
               n_particles_i=(int *)SID_malloc(sizeof(int)*(*n_groups_i));
            if(n_particles_i!=NULL)
               SID_fread_ordered(n_particles_i,sizeof(int),(size_t)(*n_groups_i),&fp_in);
            else
               SID_fskip(sizeof(int),(*n_groups_i),&fp_in);
            if(mode==MATCH_GROUPS){
               if(n_sub_group_i!=NULL)
                  SID_fread_ordered(n_sub_group_i,sizeof(int),(size_t)(*n_groups_i),&fp_in);
               else
                  SID_fskip(sizeof(int),(*n_groups_i),&fp_in);
            }
         }
         counter++;
      }
      else if(i_read_file==j_read_in){
         SID_fread(n_groups_j,sizeof(int),1,&fp_in);
         if((*n_groups_j)>0){
            if(flag_alloc_n_particles_j)
               n_particles_j=(int *)SID_malloc(sizeof(int)*(*n_groups_j));
            if(n_particles_j!=NULL)
               SID_fread_ordered(n_particles_j,sizeof(int),(size_t)(*n_groups_j),&fp_in);
            else
               SID_fskip(sizeof(int),(*n_groups_j),&fp_in);
            if(mode==MATCH_GROUPS){
               if(n_sub_group_j!=NULL)
                  SID_fread_ordered(n_sub_group_j,sizeof(int),(size_t)(*n_groups_j),&fp_in);
               else
                  SID_fskip(sizeof(int),(*n_groups_j),&fp_in);
            }
         }
         counter++;
      }
      else{
         SID_fread(&n_groups_in,sizeof(int),1,&fp_in);
         if(n_groups_in>0){
            SID_fskip(sizeof(int),n_groups_in,&fp_in);
            if(mode==MATCH_GROUPS)
               SID_fskip(sizeof(int),n_groups_in,&fp_in);
         }
      }
   }
   SID_fclose(&fp_in);

   // Read the matching file
   char filename_cat1[256];
   char filename_cat2[256];
   char filename_in_dir_snap[256];
   sprintf(filename_cat1,"%03d",i_read_in);
   sprintf(filename_cat2,"%03d",j_read_in);
   sprintf(filename_in_dir_snap,"%s/%s",filename_in_dir,filename_cat1);
   if(filename_in_dir!=NULL)
      sprintf(filename_in,"%s/%sgroup_matches_%s_%s.dat",filename_in_dir_snap,group_text_prefix,filename_cat1,filename_cat2);
   else
      sprintf(filename_in,"%s_%sgroup_matches_%s_%s.dat",filename_in_name,    group_text_prefix,filename_cat1,filename_cat2);

   SID_fopen(filename_in,"r",&fp_in);
   SID_fread(&i_read_file,sizeof(int),1,&fp_in);
   SID_fread(&j_read_file,sizeof(int),1,&fp_in);
   SID_fread(n_groups_i,  sizeof(int),1,&fp_in);
   SID_fread(n_groups_j,  sizeof(int),1,&fp_in);

   // Read matching data
   SID_fread(match_ids,  sizeof(int),   (*n_groups_i),&fp_in);
   SID_fread(match_index,sizeof(size_t),(*n_groups_i),&fp_in);
   SID_fread(match_score,sizeof(float), (*n_groups_i),&fp_in);
   SID_fclose(&fp_in);

   // If one of the catalogs is empty, set to no-match defaults
   if((*n_groups_i)<=0 || (*n_groups_j)<=0){
      for(int i_halo=0;i_halo<(*n_groups_i);i_halo++){
         match_ids[i_halo]  =-1;
         match_score[i_halo]= 0.;
      }
      if(match_flag_two_way!=NULL){
         for(int i_halo=0;i_halo<(*n_groups_i);i_halo++)
            match_flag_two_way[i_halo]=FALSE;
      }
   }
   else{
      // If we are reading groups, nullify all matches
      //    between halos with no substructures.
      int i_halo;
      if(mode==MATCH_GROUPS){
         size_t *match_index_temp;
         for(i_halo=0;i_halo<(*n_groups_i);i_halo++){
            if(n_sub_group_i[i_halo]<=0){
               match_ids[i_halo]  =-1;
               match_score[i_halo]= 0.;
            }
            else if(match_ids[i_halo]>=0 && (*n_groups_j)>0){
               if(n_sub_group_j[match_ids[i_halo]]<=0){
                  match_ids[i_halo]  =-1;
                  match_score[i_halo]= 0.;
               }
            }
         }
         merge_sort(match_ids,(size_t)(*n_groups_i),&match_index_temp,SID_INT,SORT_COMPUTE_INDEX,SORT_COMPUTE_NOT_INPLACE);
         memcpy(match_index,match_index_temp,(*n_groups_i)*sizeof(size_t));
         SID_free(SID_FARG match_index_temp);
      }

      // Apply a goodness-of-fit criterion and check that the maximum allowed score has not been exceeded
      for(i_halo=0;i_halo<(*n_groups_i);i_halo++){
         if(match_ids[i_halo]>=0){
            if(flag_reject_bad_matches && !check_validity_of_match(n_particles_i[i_halo],match_score[i_halo]))
               match_ids[i_halo]=-1;
         }
      }

      // Since we may have changed some matches with the goodness 
      //    of fit criterion, we need to re-perform the sort
      size_t *match_index_temp=NULL;
      merge_sort(match_ids,(size_t)(*n_groups_i),&match_index_temp,SID_INT,SORT_COMPUTE_INDEX,SORT_COMPUTE_NOT_INPLACE);
      memcpy(match_index,match_index_temp,(*n_groups_i)*sizeof(size_t));
      SID_free(SID_FARG match_index_temp);

      // Determine if the matches are two-way if we have been asked to check this
      if(match_flag_two_way!=NULL && (*n_groups_i)>0){

         // We're going to need the particle counts in the target catalog for checking the goodness of return matches.  Make sure we have them.
         if(n_particles_j==NULL)
            SID_trap_error("Target catalog halo sizes are not defined in read_matches() but are needed for checking two-way match flags.",ERROR_LOGIC);

         // Flip the file names for reading the return matches
         sprintf(filename_in_dir_snap,"%s/%s",filename_in_dir,filename_cat2);
         if(filename_in_dir!=NULL)
            sprintf(filename_in,"%s/%sgroup_matches_%s_%s.dat",filename_in_dir_snap,group_text_prefix,filename_cat2,filename_cat1);
         else
            sprintf(filename_in,"%s_%sgroup_matches_%s_%s.dat",filename_in_name,    group_text_prefix,filename_cat2,filename_cat1);

         // Open two files, one for reading the IDs and one for matching the scores of the matching file
         int i_read_file_check;
         int j_read_file_check;
         int n_groups_i_check;
         int n_groups_j_check;
         SID_fp fp_check_ids;
         SID_fp fp_check_score;
         SID_fopen(filename_in,"r",&fp_check_ids);
         SID_fopen(filename_in,"r",&fp_check_score);
         SID_fread(&j_read_file_check,sizeof(int),1,&fp_check_ids);
         SID_fread(&i_read_file_check,sizeof(int),1,&fp_check_ids);
         SID_fread(&n_groups_j_check, sizeof(int),1,&fp_check_ids);
         SID_fread(&n_groups_i_check, sizeof(int),1,&fp_check_ids);

         // Check that we have the right files
         if(n_groups_i_check!=(*n_groups_i))
            SID_trap_error("Source halo counts don't match (ie. %d!=%d) in two-way check in read_matches().",ERROR_LOGIC,n_groups_i_check,(*n_groups_i));
         if(n_groups_j_check!=(*n_groups_j))
            SID_trap_error("Target halo counts don't match (ie. %d!=%d) in two-way check in read_matches().",ERROR_LOGIC,n_groups_j_check,(*n_groups_j));
         if(i_read_file_check!=i_read_file)
            SID_trap_error("Source file numbers don't match (ie. %d!=%d) in two-way check in read_matches().",ERROR_LOGIC,i_read_file_check,i_read_file);
         if(j_read_file_check!=j_read_file)
            SID_trap_error("Target file numbers don't match (ie. %d!=%d) in two-way check in read_matches().",ERROR_LOGIC,j_read_file_check,j_read_file);

         // Skip to the beginning of the relevant block for the score-reading file pointer
         SID_fskip(sizeof(int),   4,            &fp_check_score); // header
         SID_fskip(sizeof(int),   (*n_groups_j),&fp_check_score); // ids
         SID_fskip(sizeof(size_t),(*n_groups_j),&fp_check_score); // indices

         // Set everything to being a one-way match unless subsequently changed
         for(i_halo=0;i_halo<(*n_groups_i);i_halo++) 
            match_flag_two_way[i_halo]=FALSE;

         // Read matching data in buffered chunks 
         int     n_good      =0;
         int     n_2way      =0;
         int     n_buffer    =1024*1024;
         int     n_chunk     =0;
         int     n_remaining =(*n_groups_j);
         int    *buffer_ids  =(int   *)SID_malloc(sizeof(int)  *n_buffer);
         float  *buffer_score=(float *)SID_malloc(sizeof(float)*n_buffer);
         for(int j_halo=0;n_remaining>0;n_remaining-=n_chunk){
            n_chunk=MIN(n_remaining,n_buffer);
            SID_fread(buffer_ids,  sizeof(int),  n_chunk,&fp_check_ids);
            SID_fread(buffer_score,sizeof(float),n_chunk,&fp_check_score);
            for(int k_halo=0;k_halo<n_chunk;k_halo++,j_halo++){
               int id_i=buffer_ids[k_halo];
               if(id_i>=0){
                  if(id_i>=(*n_groups_i))
                     SID_trap_error("Allowed matching index has been exceeded i(ie %d>=%d) while determining two-way match flags.",
                                    ERROR_LOGIC,id_i,(*n_groups_i));
                  // Do this check first to avoid having to check if both needed n_particles_* references are defined
                  int id_j=match_ids[id_i];
                  if(id_j==j_halo){
                     if(!flag_reject_bad_matches || check_validity_of_match(n_particles_j[j_halo],buffer_score[k_halo])){
                        match_flag_two_way[id_i]=TRUE; 
                        n_2way++;
                     }
                     n_good++;
                  }
               }
            }
         }
         //SID_log("n_good=%d n_2way=%d",SID_LOG_COMMENT,n_good,n_2way);
         SID_fclose(&fp_check_ids);
         SID_fclose(&fp_check_score);
         SID_free(SID_FARG buffer_ids);
         SID_free(SID_FARG buffer_score);
      }
   }

   // If any of these arrays are temporary, free them.
   if(flag_alloc_n_sub_i)
      SID_free(SID_FARG n_sub_group_i);
   if(flag_alloc_n_sub_j)
      SID_free(SID_FARG n_sub_group_j);
   if(flag_alloc_n_particles_i)
      SID_free(SID_FARG n_particles_i);
   if(flag_alloc_n_particles_j)
      SID_free(SID_FARG n_particles_j);
}
Example #27
0
void Test_tablica::wykonaj()
{
    timer stoper;
    stoper.przygotuj();
    for(int i=0; i<10; i++)
    {
        stoper.start_clock();
        wykonaj_quicksort1(tab,0,rozmiar-1);
        stoper.stop_clock();
        stoper.get_time();
        stoper.dodaj_sume();
        reset();
    }
    cout<<"pivot w srodku"<<endl;
    cout<<"sredni czas dla posortowania "<<rozmiar<<" elementow to: \t"<<stoper.get_suma()/10<<endl;
    stoper.przygotuj();
    for(int i=0; i<10; i++)
    {
        stoper.start_clock();
        wykonaj_quicksort2(tab,0,rozmiar-1);
        stoper.stop_clock();
        stoper.get_time();
        stoper.dodaj_sume();
        reset();
    }
    cout<<"pivot na poczatku"<<endl;
    cout<<"sredni czas dla posortowania "<<rozmiar<<" elementow to: \t"<<stoper.get_suma()/10<<endl;
    stoper.przygotuj();
    for(int i=0; i<10; i++)
    {

        stoper.start_clock();
        merge_sort(tab,0,rozmiar-1);
        stoper.stop_clock();
        stoper.get_time();
        stoper.dodaj_sume();
        reset();
    }
    cout<<"Mergesort - pivot w srodku"<<endl;
    cout<<"sredni czas dla posortowania "<<rozmiar<<" elementow to: \t"<<stoper.get_suma()/10<<endl;
    stoper.przygotuj();
    for(int i=0; i<10; i++)
    {

        stoper.start_clock();
        merge_sort2(tab,0,rozmiar-1);
        stoper.stop_clock();
        stoper.get_time();
        stoper.dodaj_sume();
        reset();
    }
    cout<<"Mergesort - pivot na poczatku"<<endl;
    cout<<"sredni czas dla posortowania "<<rozmiar<<" elementow to: \t"<<stoper.get_suma()/10<<endl;
    stoper.przygotuj();
    for(int i=0; i<10; i++)
    {

        stoper.start_clock();
        merge_sort3(tab,0,rozmiar-1);
        stoper.stop_clock();
        stoper.get_time();
        stoper.dodaj_sume();
        reset();
    }
    cout<<"Mergesort - pivot losowo"<<endl;
    cout<<"sredni czas dla posortowania "<<rozmiar<<" elementow to: \t"<<stoper.get_suma()/10<<endl;
}
Example #28
0
// sets initial strategies, roles, valuations and payoffs
void set_init_xrvpi()
{
  int g, i;
  double v_sum; 

  for(g = 0; g < G; g++){     // through each group                               
    for(pi_g[g] = 0, v_sum = 0, i = 0; i < N; i++){   // through each individual in a group      
      x[g][i] = U01()*0.05;              // initialize strategy vector for all individuals      
      pi[g][i] = 1.0;                           // set initial payoffs for each individual to 1   
      Api[g][i] = 0;
      // start calculation of valuations of each individual
#if !PUNISH  
      V[g][i]  = pow(N - i, Delta);                // rank based valuations
#if EGALITARIAN
      V[g][i] = 1;
#endif
      v_sum += V[g][i];                            // sum of valuations of individuals in a group for normalization 
#endif      
    }              
    pi_g[g] = 1;
#if !PUNISH
    // normalize valuations
    for(i = 0; i < N; i++){  // through each individual 
      V[g][i] /= v_sum;         // normalize valuations      
    }     
#endif
  }
  
#if PUNISH

  int j;
  double *ss = malloc(N*sizeof(double));            // scratch space for strength sorting
    
  for(g = 0; g < G; g++){     // through each group          
    
    for( i = 0; i < N; i++){ ss[i] = U01();  /*ss[i] = 1. - i/(double)N;*/}
    merge_sort(ss, N);   // sort strength                     
    for(v_sum = 0, i = 0; i < N; i++){   // through each individual in a group  
      S[g][i] = ss[N-i-1];                      // assign strength in descending order 
      dxi[g][i] = U01()*0.05;
#if AGGR
      dsi[g][i] = 1 - U01()*0.05;              // setting value near to 1   
#else
      dsi[g][i] = 0;
#endif
      
#if EGALITARIAN
      S[g][i] = 1;
      V[g][i] = 1;                              // same valuations
#else
      V[g][i] = pow(S[g][i], Beta);             // strength based valuations
#endif
      v_sum += V[g][i];
    }
    // normalize valuations
    for(i = 0; i < N; i++){  // through each individual 
      V[g][i] /= v_sum;         // normalize valuations      
    }  
  }

  // computing Sij matrix for all groups
  for(g = 0; g < G; g++){
    for(i = 0; i < N; i++){
      for(j = 0; j < N; j++){
	if( i == j) continue;
	Sij[g][i][j] = S0 *( exp( Phi*(S[g][j] - S[g][i]) ) );
      }   
    }
  }  
  free(ss);
#endif
}
Example #29
0
// sort in place, i.e. A will be reordered
void merge_sort(int16_t *A, int16_t A_len) {
    indent_in();
    indent();
    Serial.print("Entering merge sort: array addr ");
    Serial.print( (int) A );
    Serial.print(" len ");
    Serial.println( A_len);
    mem_info("");

    assert_free_mem_ok(128, "merge_sort");

    if ( A_len < 2 ) {
        indent_out();
        return;
        }

    if ( A_len == 2 ) {
        if ( A[0] > A[1] ) {
            int temp = A[0];
            A[0] = A[1];
            A[1] = temp;
            }
        indent_out();
        return;
        }

    // split A in half, sort left, sort right, then merge
    // left half is:  A[0], ..., A[split_point-1]
    // right half is: A[split_point], ..., A[A_len-1]

    int split_point = A_len / 2;

    indent();
    Serial.println("Doing left sort");

    merge_sort(A, split_point);

    mem_info("After left sort");

    indent();
    Serial.println("Doing right sort");

    merge_sort(A+split_point, A_len-split_point);

    mem_info("After right sort");

    // don't need the merging arrat S until this point
    int *S = (int *) malloc( A_len * sizeof(int) );

    assert_malloc_ok(S, "Cannot get merge buffer");

    mem_info("Doing merge");

    merge(A, split_point, A+split_point, A_len-split_point, S);

    for (int i=0; i < A_len; i++) {
        A[i] = S[i];
        }

    // now we are done with it
    free(S);

    mem_info("After free");
    indent_out();
    }
Example #30
0
 ListNode* sortList(ListNode* head) 
 {
     if (head == NULL) return head;
     return merge_sort(head);
 }