Exemple #1
0
int main(int argc, char** argv) {
  MPI_Status status;
	int i, n;
	int* data, *temp;
	clock_t start, end;
	double elapsed_time, t1, t2;

//MPI
  MPI_Init(NULL, NULL);
  int world_rank;
  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  int world_size;
  MPI_Comm_size(MPI_COMM_WORLD, &world_size);

// Create data
	data = (int *)malloc(sizeof(int)*N);
	temp = (int *)malloc(sizeof(int)*N);
  if (world_rank == 0)
  {
	 if (data == NULL) {
		printf("Fail to malloc\n");
		exit(1);
	 }
	for (i=N-1; i>=0; i--)
		data[N-1-i] = i;
// Check sorted
    if (isSorted(data, N))
    printf("Array is sorted\n");
    else
    printf("Array is NOT sorted\n");
  }

	
//Sort Part
  MPI_Barrier(MPI_COMM_WORLD);
  
  t1 = MPI_Wtime();

  int s = N/world_size;
  MPI_Bcast(&s,1,MPI_INT,0,MPI_COMM_WORLD);
  int * chunk = (int *)malloc(s*sizeof(int));
  MPI_Scatter(data,s,MPI_INT,chunk,s,MPI_INT,0,MPI_COMM_WORLD);

  bubbleSort(chunk,s);

// merge
  int step = 1;
  while(step<world_size)
  {
    if(world_rank%(2*step)==0)
    {
      if(world_rank+step<world_size)
      {
        int m;
        MPI_Recv(&m,1,MPI_INT,world_rank+step,0,MPI_COMM_WORLD,&status);
        int * other;
        other = (int *)malloc(m*sizeof(int));
        MPI_Recv(other,m,MPI_INT,world_rank+step,0,MPI_COMM_WORLD,&status);
        chunk = merge(chunk,s,other,m);
        s = s+m;
      } 
    }
    else
    {
      int near = world_rank-step;
      MPI_Send(&s,1,MPI_INT,near,0,MPI_COMM_WORLD);
      MPI_Send(chunk,s,MPI_INT,near,0,MPI_COMM_WORLD);
      break;
    }
    step = step*2;
  }

  if(world_rank == 0){
    if (isSorted(chunk, N))
      printf("Array is sorted\n");
    else
      printf("%d : Array is NOT sorted\n", world_size); 
    t2 = MPI_Wtime();
    printf( "Elapsed time MPI_Wtime is %f\n", t2 - t1 );
  }

  MPI_Finalize();	
	return 0;
}
int main() 
{
    const unsigned long int N = 100;
    
    std::cout << N << std::endl;

    srand((int) time(NULL));
    
    int * a = new int[N];
    int * aux = new int[N];

    copiaNumeros(a,N);
    
    for (int i = 0; i < N; ++i) 
    {
        aux[i] = a[i];
    }

    auto begin = std::chrono::high_resolution_clock::now();
    bubbleSort(a, N);
    auto end = std::chrono::high_resolution_clock::now();
    auto tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Bubble: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    cocktailSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Cocktail: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    insertionSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Insertion: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    bucketSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Bucket: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    countingSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Counting: "<<tiempo.count()<<std::endl;

    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    mergeSort(a, 0, N-1, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Merge: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    radixSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Radix: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    shellSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Shell: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    selectionSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Selection: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    quickSort(a, 0, N-1);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Quick: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    heap_sort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Heap: "<<tiempo.count()<<std::endl;

    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    binarySort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Binary: "<<tiempo.count()<<std::endl;

    delete a;
    delete aux;

    return 0;
}
Exemple #3
0
void ItemStorage::sort() {
	bubbleSort(storage, slot_number);
}
Exemple #4
0
int aslr_sumup(unsigned int i){
	bubbleSort((addr_size*)aslrtab+i*num_samples,num_samples);
	maxrep(i);

	return 0;
}
Exemple #5
0
void test_sort_character_data(){
	char data[5] = {'d','b','c','a','e'};
	char expected[5] = {'a','b','c','d','e'};
	bubbleSort(data, 5, sizeof(char), compareChar);
	ASSERT(0 == memcmp(data,expected,sizeof(expected)));
}
Exemple #6
0
void InsertionSet::execute(BasicBlock* block)
{
    bubbleSort(m_insertions.begin(), m_insertions.end());
    executeInsertions(block->m_values, m_insertions);
}
int main(int argc, char** argv) {
	int i, n;
	int* A, *temp;
	clock_t start, end;
	double elapsed_time, t1, t2;

	MPI_Init(NULL, NULL);
	int world_rank, world_size;
	MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
	MPI_Comm_size(MPI_COMM_WORLD, &world_size);
	
	n = world_size;
	int chunkSize = N / world_size;
	int start_index = world_rank * chunkSize;

	t1 = MPI_Wtime();
	A = (int *)malloc(sizeof(int)*chunkSize);
	temp = (int *)malloc(sizeof(int)*N);
	if (A == NULL) {
		printf("Fail to malloc\n");
		exit(1);
	}
	for (i=chunkSize-1; i>=0; i--)
		A[chunkSize-1-i] = i + start_index;
	
	if (isSorted(A, chunkSize))
	  printf("Array is sorted\n");
	else
	  printf("Array is NOT sorted\n");
	
	bubbleSort(A, chunkSize);

	if (world_rank == 0) {
		int rank;
		int *partial[n];
		printArray(A, 5);
		partial[0] = A;
		for (rank = 1; rank < world_size; rank++) {
			int* rev = (int *)malloc(sizeof(int)*chunkSize);
			MPI_Recv(rev, chunkSize, MPI_INT, rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
			printArray(rev, 5);
			partial[rank] = rev;
		}

		temp = multiMerge(partial, N, n);	      

		if (isSorted(temp, N))
		  printf("Array is sorted\n");
		else
		  printf("Array is NOT sorted\n");	

		t2 = MPI_Wtime();
		printf( "Elapsed time MPI_Wtime is %f\n", t2 - t1 ); 
		//printArray(temp, N);
	}
	else if (world_rank != 0) {
		MPI_Send(A, chunkSize, MPI_INT, 0, 0, MPI_COMM_WORLD);
	}

	MPI_Finalize();
	return 0;
}
Exemple #8
0
void test_sort_only_one_integer_element(){
	int data[1] = {5};
	int expected[1] = {5};
	bubbleSort(data, 1, sizeof(int), compareInt);
	ASSERT(0 == memcmp(data,expected,sizeof(expected)));
}
Exemple #9
0
void main()
{
	int a[1000]; /*declarete array whith integer values*/
	gen_array(a); /*fill an array of random numbers*/


	printf("Test bubble sorting\n");
	printArray(a, ARRAY_SIZE(a));

	clock_t theStartt = clock(); /*starting clock*/
	bubbleSort(a, ARRAY_SIZE(a));
	clock_t theEndt = clock(); /*finish clock*/
	printArray(a, ARRAY_SIZE(a));
	printf ("time of Bubble sorting: %.10lf\n", (double)(theEndt - theStartt)/CLOCKS_PER_SEC);


	gen_array(a); /*assigned array new value*/


	printf("\nTest selection sorting\n");
	printArray(a, ARRAY_SIZE(a));

	clock_t theStart1 = clock(); /*starting clock*/
	selectionSort(a, ARRAY_SIZE(a));
	clock_t theEnd1 = clock(); /*finish clock*/
	printArray(a, ARRAY_SIZE(a));
	printf ("time of Selection sorting: %.10lf\n", (double)(theEnd1 - theStart1)/CLOCKS_PER_SEC);


	gen_array(a); /*assigned array new value*/


	printf("\nTest insertion sorting\n");
	printArray(a, ARRAY_SIZE(a));

	clock_t theStart0 = clock(); /*starting clock*/
	insertionSort(a, ARRAY_SIZE(a));
	clock_t theEnd0 = clock(); /*finish clock*/
	printArray(a, ARRAY_SIZE(a));
	printf ("time of Inserton sorting: %.10lf\n", (double)(theEnd0 - theStart0)/CLOCKS_PER_SEC);


	gen_array(a); /*assigned array new value*/


	printf("\nTest Shell sorting\n");
	printArray(a, ARRAY_SIZE(a));

	clock_t theStart = clock(); /*starting clock*/
	shellSort(a, ARRAY_SIZE(a));
	clock_t theEnd = clock(); /*finish clock*/
	printArray(a, ARRAY_SIZE(a));
	printf ("time of Shell sorting: %.10lf\n", (double)(theEnd - theStart)/CLOCKS_PER_SEC);
	
	gen_array(a);

	printf("\nTest quickSort\n");
	printArray(a, ARRAY_SIZE(a));

	clock_t theStart3 = clock();
	quickSort(a, ARRAY_SIZE(a));
	clock_t theEnd3 = clock();
	printArray(a, ARRAY_SIZE(a));
	printf ("time of quickSort : %.10lf\n", (double)(theEnd3 - theStart3)/CLOCKS_PER_SEC);
}
Exemple #10
0
int average(int *array1, int size, int code)
{
	int array2[size];
	int array3[size];
	int array4[size];
	int array5[size];
	int array6[size];
	int array7[size];
	int array8[size];
	int array9[size];
	int array10[size];
	int i;
	double time = 0;
	clock_t start_t, end_t;
	
	//copies array1 to the rest of the arrays
	for(i = 0; i <= size; i++)
	{
		array2[i] = array1[i];
		array3[i] = array1[i];
		array4[i] = array1[i];
		array5[i] = array1[i];
		array6[i] = array1[i];
		array7[i] = array1[i];
		array8[i] = array1[i];
		array9[i] = array1[i];
	}

	switch(code)
	{
		case 1: start_t = clock();
				insertionSort(array1, size);	
				insertionSort(array2, size);	
				insertionSort(array3, size);
				insertionSort(array4, size);	
				insertionSort(array5, size);	
				insertionSort(array6, size);	
				insertionSort(array7, size);	
				insertionSort(array8, size);	
				insertionSort(array9, size);	
				insertionSort(array10, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		case 2: start_t = clock();
				selectionSort(array1, size);	
				selectionSort(array2, size);	
				selectionSort(array3, size);	
				selectionSort(array4, size);	
				selectionSort(array5, size);	
				selectionSort(array6, size);	
				selectionSort(array7, size);	
				selectionSort(array8, size);	
				selectionSort(array9, size);	
				selectionSort(array10, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		case 3: start_t = clock();
				bubbleSort(array1, size);	
				bubbleSort(array2, size);	
				bubbleSort(array3, size);	
				bubbleSort(array4, size);	
				bubbleSort(array5, size);	
				bubbleSort(array6, size);	
				bubbleSort(array7, size);	
				bubbleSort(array8, size);	
				bubbleSort(array9, size);	
				bubbleSort(array10, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		case 4: start_t = clock();
				mergeSort(array1, 0, size);	
				mergeSort(array2, 0, size);	
				mergeSort(array3, 0, size);	
				mergeSort(array4, 0, size);	
				mergeSort(array5, 0, size);	
				mergeSort(array6, 0, size);	
				mergeSort(array7, 0, size);	
				mergeSort(array8, 0, size);	
				mergeSort(array9, 0, size);	
				mergeSort(array10, 0, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		case 5: start_t = clock();
				quickSort(array1, 0, size);	
				quickSort(array2, 0, size);	
				quickSort(array3, 0, size);	
				quickSort(array4, 0, size);	
				quickSort(array5, 0, size);	
				quickSort(array6, 0, size);	
				quickSort(array7, 0, size);	
				quickSort(array8, 0, size);	
				quickSort(array9, 0, size);	
				quickSort(array10, 0, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		default: puts("command not found");
	}

	return time / 10;
}
//Huge main function.
int main(int argc, char *argv[]) {
  if (argc < 3){                                                      //if you don't type enough arguments
    printf("Sockets client, usage:\n");
    printf("sockets_client  {IP-address} {port} \n");
    return 0;
  } 
  else {
    free(server);
    server = malloc((strlen(argv[1] + 1) * sizeof(char)));
    strcpy(server, argv[1]);
    portno = atoi(argv[2]);
  }

  int c;
  while(1){
    if(screen == 0){ 
      CATEGORY = 8;
      currentRecord = 0;
      recordView = 0;
      xt_par0(XT_CLEAR_SCREEN);
      lifeTracker();
      xt_par2(XT_SET_ROW_COL_POS,row = 8, col = 2);
    }
    while(screen == 0) {
      while((c = getkey()) == KEY_NOTHING);
        if(c == KEY_F9) screen = 3;
        else if(c == KEY_F3 && maxRecord > 0 && col == 20) screen = 4;
        else if(c == KEY_DOWN) {
          if(col == 2 && row >= 8 && row < catCounter + 7){ 
            xt_par2(XT_SET_ROW_COL_POS,CATEGORY = ++row,col);
  	        updateRecords(recordView);
  	      }
          if(col == 20 && row >= 7 && row <= tempCounter * 5 + 1){
            if(row < 22){
              xt_par2(XT_SET_ROW_COL_POS,row+=5,col);
              ++currentRecord;
  	       }
            else if(recordView < tempCounter-4){ 
              ++recordView;
              if(search == 1) searchResults(recordView);
    	        else updateRecords(recordView);
                xt_par2(XT_SET_ROW_COL_POS,row=22,col);
                ++currentRecord;
            }
          }
        	if(col > 94 && col < 120){
        	  if(row == 9)
        	    xt_par2(XT_SET_ROW_COL_POS,row = 12,col = 95);
        	  else if(row == 12)
        	    xt_par2(XT_SET_ROW_COL_POS,row = 13,col = 95);
        	  else if(row == 13)
        	    xt_par2(XT_SET_ROW_COL_POS,row = 16,col);
            else if(row < 20) 
              xt_par2(XT_SET_ROW_COL_POS,++row,col);
            else if(row == 20 && col < 110)
              xt_par2(XT_SET_ROW_COL_POS,++row,col);
            else if(row == 20 && col > 110)
              xt_par2(XT_SET_ROW_COL_POS,++row,col = 109);
        	}
        }
        else if(c == KEY_UP){
          if(col == 2 && row > 8 && row <= 18){
            xt_par2(XT_SET_ROW_COL_POS,CATEGORY = --row,col);
        	  updateRecords(recordView);
        	}
          if(col == 20 && row >= 7 && row < 24){
            if(row <= 24 && row > 7){
              xt_par2(XT_SET_ROW_COL_POS,row-=5,col);
              --currentRecord;
  	        }
            else if(recordView > 0){
              --recordView;
            if(search == 1) searchResults(recordView);
      	    else updateRecords(recordView);
                xt_par2(XT_SET_ROW_COL_POS,row=7,col);
                --currentRecord;
            }
          }
        	if(row > 9 && col > 94 && col < 120){
        	  if(row == 12)
        	    xt_par2(XT_SET_ROW_COL_POS,row = 9,col = 95);
        	  else if(row == 13)
        	    xt_par2(XT_SET_ROW_COL_POS,row = 12,col = 95);
            else if(row == 16) 
              xt_par2(XT_SET_ROW_COL_POS, row = 13, col = 95);
        	  else if(row < 22)
        	    xt_par2(XT_SET_ROW_COL_POS, --row, col);
        	}
        }
        else if(c == KEY_ENTER && col > 94 && col < 120 && row > 12 && row < 18) xt_par2(XT_SET_ROW_COL_POS,++row,col=95);
        else if((c == KEY_LEFT || c == KEY_RIGHT) && col == 2) {
        	CATEGORY = row;
        	updateRecords(recordView);
        	xt_par2(XT_SET_ROW_COL_POS,row=7,col=20);
        }
        else if((c == KEY_LEFT || c == KEY_RIGHT) && col == 20) {
          xt_par2(XT_SET_ROW_COL_POS,row=CATEGORY,col=2);
          if (search == 1) clearSearch();
          currentRecord = recordView = search = 0;
  	      updateRecords(recordView);
        }
        else if(c == KEY_LEFT && col >= 95) {
          if(col > 95)
            xt_par2(XT_SET_ROW_COL_POS,row,--col);
          else if(row == 13 && col == 95) 
            xt_par2(XT_SET_ROW_COL_POS,--row,col = 101);
          else if(row >= 17 && row <= 21 && col == 95) 
            xt_par2(XT_SET_ROW_COL_POS,--row, col = 119);
        }
        else if(c == KEY_RIGHT && col > 94) {
          if(row == 9 && col < 112) 
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          else if(row == 12 && col < 101) 
              xt_par2(XT_SET_ROW_COL_POS,row,++col);
            else if(row == 12 && col == 101) 
              xt_par2(XT_SET_ROW_COL_POS,++row,col = 95);
          else if(row == 13 && col < 112) 
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          else if(row >= 16 && row < 21 && col < 119)
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          else if(row == 21 && col < 109) 
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          else if(row >= 16 && row <= 21 && col == 119) 
            xt_par2(XT_SET_ROW_COL_POS,++row,col = 95);
        }
        else if(c == KEY_DELETE) {
          putchar(' ');
          if(row == 9) Category[col - 95] = ' ';
          else if(row == 12) Title[col - 95] = ' ';
          else if(row == 13) Title[col - 88] = ' ';
          else if(row >= 16 && row < 22) Body[(row - 16) * 25 + col - 95] = ' ';
        }
        else if(c == KEY_BACKSPACE && col >= 95) {
          if((row == 9 || row == 12) && col > 95) {
	    xt_par2(XT_SET_ROW_COL_POS,row,--col);
            putchar(' ');
            Category[col - 95] = ' ';
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
          else if((row == 9 || row == 12) && col == 95) {
            putchar(' ');
            Title[col - 95] = ' ';
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
          else if(row == 13 && col > 95) {
	          xt_par2(XT_SET_ROW_COL_POS,row,--col);
            putchar(' ');
            Title[col - 88] = ' ';
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
          else if(row == 13 && col == 95) {
	          xt_par2(XT_SET_ROW_COL_POS,--row,col = 101);
            putchar(' ');
            Title[col - 88] = ' ';
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
          else if(row >= 16 && row < 22 && col > 95) {
	          xt_par2(XT_SET_ROW_COL_POS,row,--col);
            putchar(' ');
            Body[(row - 16) * 25 + col - 95] = ' ';
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
          else if(row == 16 && col == 95) {
            putchar(' ');
            Body[(row - 16) * 25 + col - 95] = ' ';
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
          else if(row > 16 && row < 22 && col == 95) {
	          xt_par2(XT_SET_ROW_COL_POS,--row,col = 119);
            putchar(' ');
            Body[(row - 16) * 25 + col - 95] = ' ';
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
        } 
        else if((c >= ' ' && c <= '~') && col >= 95 && col < 120){
          if(row == 9 && col < 112) {
            putchar(c);
            Category[col - 95] = c;
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          }
          else if(row == 9 && col == 112) {
            putchar(c);
            Category[col - 95] = c;
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
          else if(row == 12 && col < 101) {
            putchar(c);
            Title[col - 95] = c;
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          }
          else if(row == 12 && col == 101) {
            putchar(c);
            Title[col - 95] = c;
            xt_par2(XT_SET_ROW_COL_POS,++row,col=95);
          }
          else if(row == 13 && col < 112) {
            putchar(c);
            Title[col - 88] = c;
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          }
          else if(row == 13 && col == 112) {
            putchar(c);
            Title[col - 88] = c;
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
          else if(row >= 16 && row < 21 && col < 119) {
            putchar(c);
            Body[(row - 16) * 25 + col - 95] = c;
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          }
          else if(row >= 16 && row < 21 && col == 119) {
            putchar(c);
            Body[(row - 16) * 25 + col - 95] = c;
            xt_par2(XT_SET_ROW_COL_POS,++row,col = 95);
          }
          else if(row == 21 && col < 109) {
            putchar(c);
            Body[(row - 16) * 25 + col - 95] = c;
            xt_par2(XT_SET_ROW_COL_POS,row,++col);
          }
          else if(row == 21 && col == 109) {
            putchar(c);
            Body[(row - 16) * 25 + col - 95] = c;
            xt_par2(XT_SET_ROW_COL_POS,row,col);
          }
        }
        else if(c == KEY_F2)
          screen = 1;
        else if(c == KEY_F4 && col == 20 && maxRecord != 0)
          screen = 2;
        else if(c == KEY_F6) {
        	if(sort == 0){
        	  bubbleSort();
        	  sort = 1;
        	}
        	else if (sort == 1){
        	  bubbleSortTime();
        	  sort = 0;
        	}
        }
        else if (c == KEY_F7){
        	if(col < 95) {
            xt_par2(XT_SET_ROW_COL_POS,row = 9,col = 95);
            for(reset = 0; reset < 29; reset++) Title[reset] = ' ';
            for(reset = 0; reset < 140; reset++) Body[reset] = ' ';
            for(reset = 0; reset < 16; reset++) Category[reset] = ' ';
          }
        	else if(Title[0] == ' ' && Body[0] == ' ' && Category[0] == ' ') {
            xt_par2(XT_SET_ROW_COL_POS,row = CATEGORY,col = 2);
            clearSearch();
            updateRecords(0);
          }
          else if(Title[0] != ' ' || Body[0] != ' ' || Category[0] != ' ') {
            clearSearch();
	          search = 1;
            searchResults(0);
            xt_par2(XT_SET_ROW_COL_POS,row = 7, col = 20);
          }
        }
    }
    if (screen == 1 || screen == 2){
      for(reset = 0; reset < 29; reset++) Title[reset] = ' ';
      for(reset = 0; reset < 140; reset++) Body[reset] = ' ';
      for(reset = 0; reset < 16; reset++) Category[reset] = ' ';
      addScreen();
      if (screen == 2){ 
        char TempBodyA[71]; 
        char TempBodyB[71];
        int k = 0;
        while(k != 70) {
      	  TempBodyA[k] = ' ';
      	  TempBodyB[k] = ' ';
      	  k++;
        }
        k = 0; 
        xt_par2(XT_SET_ROW_COL_POS, row = 12, col = 25);
        xt_par0(XT_CH_GREEN);
        printf("Record %d (%s)", currentRecord+1, catStorage[currentRecord].timedate); //get the time using myui1
        xt_par0(XT_CH_WHITE);
        xt_par2(XT_SET_ROW_COL_POS, row = 14, col = 25);
        printf("%s", catStorage[currentRecord].category);
        int j = 0; 
        while(catStorage[currentRecord].body[j] != '\0'){
          if (j < 70) TempBodyA[j] = catStorage[currentRecord].body[j];
          else if (j < 140) TempBodyB[j%70] = catStorage[currentRecord].body[j];
          j++;
        }
        TempBodyA[70] = '\0';
        TempBodyB[70] = '\0';
        xt_par2(XT_SET_ROW_COL_POS, row = 16, col = 25);
        printf("%s", catStorage[currentRecord].subject);
        xt_par0(XT_CH_WHITE);
        xt_par2(XT_SET_ROW_COL_POS, row = 19, col = 25);
        printf("%s", TempBodyA); 
        xt_par2(XT_SET_ROW_COL_POS, row = 20, col = 25); 
        printf("%s", TempBodyB); 
        xt_par2(XT_SET_ROW_COL_POS, row = 14, col = 25); 
        strncpy(Title, catStorage[currentRecord].subject, sizeof(Title));
        strncpy(Body, catStorage[currentRecord].body, sizeof(Body));
        strncpy(Category, catStorage[currentRecord].category, sizeof(Category));
      }
    } 
    while(screen == 1 || screen == 2) {
      while((c = getkey()) == KEY_NOTHING);
      if (c == KEY_F9){
        screen = 0;
        xt_par0(XT_CLEAR_SCREEN);
      }
      else if (c == KEY_DOWN){
        if(row == 14) 
          xt_par2(XT_SET_ROW_COL_POS, row = 16, col = 25);
        else if(row == 16)
          xt_par2(XT_SET_ROW_COL_POS,row = 19,col = 25);
    	else if(row < 20)
    	  xt_par2(XT_SET_ROW_COL_POS,++row,col);
      }
      else if (c == KEY_UP){    
        if(row == 16)
          xt_par2(XT_SET_ROW_COL_POS, row = 14, col = 25);
        if(row == 19)
          xt_par2(XT_SET_ROW_COL_POS,row = 16,col = 25);
    	else if(row == 20)
    	  xt_par2(XT_SET_ROW_COL_POS,--row,col);
      }
      else if(c == KEY_LEFT && col > 25 && col < 95) xt_par2(XT_SET_ROW_COL_POS,row,--col);
      else if(c == KEY_LEFT && col == 25 && row == 20) xt_par2(XT_SET_ROW_COL_POS,--row,col=94);
      else if(c == KEY_RIGHT && col > 24 && col < 37 && row == 14) xt_par2(XT_SET_ROW_COL_POS,row,++col);
      else if(c == KEY_RIGHT && col > 24 && col < 53 && row == 16) xt_par2(XT_SET_ROW_COL_POS,row,++col);
      else if(c == KEY_RIGHT && col > 24 && col < 94 && row > 18) xt_par2(XT_SET_ROW_COL_POS,row,++col);
      else if(c == KEY_RIGHT && col == 94 && row == 19) xt_par2(XT_SET_ROW_COL_POS,++row,col=25);   
      else if (c == KEY_ENTER && row > 18 && row < 20) xt_par2(XT_SET_ROW_COL_POS,++row,col=25);      
      else if (c == KEY_BACKSPACE && col >= 25 && col < 95 && ((row > 18 && row < 21) || row == 16 || row == 14)){
      	if(row == 14 && col > 25 && col < 39) {
      	  xt_par2(XT_SET_ROW_COL_POS,row,--col);
      	  putchar(' ');
      	  Category[col - 25] = ' ';
      	}
      	else if(row == 16 && col > 25 && col <= 54) {
      	  xt_par2(XT_SET_ROW_COL_POS,row,--col);
      	  putchar(' ');
      	  Title[col - 25] = ' ';
      	}
      	else if(row == 19 && col > 25 && col <= 95) {
      	  xt_par2(XT_SET_ROW_COL_POS,row,--col);
      	  putchar(' ');
      	  Body[col - 25] = ' ';
      	}
      	else if(row == 20 && col > 25 && col <= 95) {
      	  xt_par2(XT_SET_ROW_COL_POS,row,--col);
      	  putchar(' ');
      	  Body[col + 45] = ' ';
      	}
      	else if(row == 20){                                          
      	  xt_par2(XT_SET_ROW_COL_POS,--row,col=94);
      	  putchar(' ');
      	  Body[69] = ' ';
      	}
	      xt_par2(XT_SET_ROW_COL_POS,row,col);
      }
      else if (c == KEY_DELETE) {
        if(row == 14 && col >= 25 && col < 38) {
      	  putchar(' ');
      	  Category[col - 25] = ' ';
	    }
    	else if(row == 16 && col >= 25 && col < 54) {
    	  putchar(' ');
    	  Title[col - 25] = ' ';
    	}
    	else if(row == 19 && col >= 25 && col <= 95) {
    	  putchar(' ');
    	  Body[col - 25] = ' ';
    	}
    	else if(row == 20 && col >= 25 && col <= 95) {
    	  putchar(' ');
    	  Body[col + 45] = ' ';
    	}
      xt_par2(XT_SET_ROW_COL_POS,row,col);
      } 
      else if((c >= ' ' && c <= '~') && col >= 25 && col < 95) {
      	if(row == 14 && col >= 25 && col < 40) {
      	  putchar(c);
      	  Category[col - 25] = c;
      	}
      	else if(row == 16 && col >= 25 && col < 54) {
      	  putchar(c);
      	  Title[col - 25] = c;
      	}
      	else if(row == 19 && col >= 25 && col <= 95) {
      	  putchar(c);
      	  Body[col - 25] = c;
      	}
      	else if(row == 20 && col >= 25 && col <= 95) {
      	  putchar(c);
      	  Body[col + 45] = c;
      	}
      	if (col < 94 && !(row == 16 && col > 52) && !(row == 14 && col > 36)){
      	  ++col; 
      	}    
      	else{ 
      	  if (row == 19)                                            
      	    xt_par2(XT_SET_ROW_COL_POS,++row,col=25);
      	  else xt_par2(XT_SET_ROW_COL_POS,row,col); 
      	}
      }
      else if(c == KEY_F2 && screen == 1 /* && there is a valid title and description */){
	      //save record to corresponding subject
        if(Title[0] != ' ' || Body[0] != ' ' || Category[0] != ' ') {
          removeBlanks();
          readmyStoreFromChildSOCKETS("add", Title, Body, Category, NULL);
        }
        int k = 0;
        while(k != 29) Title[k++] = ' ';
        k = 0;
        while(k != 140) Body[k++] = ' ';
        k = 0;
        while(k != 15) Category[k++] = ' ';
        maxRecord++;
        screen = 0;
      }
      else if(c == KEY_F2 && screen == 2 /* && there has been a valid change in the record */){
      //update record
	    removeBlanks();
      char str[80];
    	for(i = 0; i < maxRecord; i++){
    	  if(strcmp(catStorage[currentRecord].subject, dataStorage[i].subject) == 0 &&
    	     strcmp(catStorage[currentRecord].body, dataStorage[i].body) == 0 &&
    	     strcmp(catStorage[currentRecord].category, dataStorage[i].category) == 0 &&
    	     strcmp(catStorage[currentRecord].timedate, dataStorage[i].timedate) == 0){//looks for corresponding record in the actual record list
    	    sprintf(str, "%d", i+1);
    	    break;
    	  }
    	}
      readmyStoreFromChildSOCKETS("edit", str, Title, Body, Category);
      int k = 0;
      while(k != 29) Title[k++] = ' ';
      k = 0;
      while(k != 140) Body[k++] = ' ';
      k = 0;
      while(k != 15) Category[k++] = ' ';
      screen = 0;
    }
  }
    if (screen == 4){
      for(reset = 0; reset < 29; reset++) Title[reset] = ' ';
      for(reset = 0; reset < 140; reset++) Body[reset] = ' ';
      for(reset = 0; reset < 16; reset++) Category[reset] = ' ';
      deleteScreen();
      if (screen == 4){ 
        char TempBodyA[71]; 
        char TempBodyB[71];
        int k = 0;
        while(k != 70) {
      	  TempBodyA[k] = ' ';
      	  TempBodyB[k] = ' ';
      	  k++;
        }
        k = 0;
        xt_par2(XT_SET_ROW_COL_POS, row = 12, col = 25);
        xt_par0(XT_CH_GREEN);
        printf("Record %d (%s)", currentRecord+1, catStorage[currentRecord].timedate); //get the time using myui1
        xt_par0(XT_CH_WHITE);
        xt_par2(XT_SET_ROW_COL_POS, row = 14, col = 25);
        printf("%s", catStorage[currentRecord].category);
        int j = 0; 
        while(catStorage[currentRecord].body[j] != '\0'){
          if (j < 70) TempBodyA[j] = catStorage[currentRecord].body[j];
          else if (j < 140) TempBodyB[j%70] = catStorage[currentRecord].body[j];
          j++;
        }
        TempBodyA[70] = '\0';
        TempBodyB[70] = '\0';
        xt_par2(XT_SET_ROW_COL_POS, row = 16, col = 25);
        printf("%s", catStorage[currentRecord].subject);
        xt_par0(XT_CH_WHITE);
        xt_par2(XT_SET_ROW_COL_POS, row = 19, col = 25);
        printf("%s", TempBodyA); 
        xt_par2(XT_SET_ROW_COL_POS, row = 20, col = 25); 
        printf("%s", TempBodyB); 
        xt_par2(XT_SET_ROW_COL_POS, row = 14, col = 25); 
        strncpy(Title, catStorage[currentRecord].subject, sizeof(Title));
        strncpy(Body, catStorage[currentRecord].body, sizeof(Body));
        strncpy(Category, catStorage[currentRecord].category, sizeof(Category));
        //print corresponding record in correct locations using myui1 
      }
    } 
    while(screen == 4) {
      while((c = getkey()) == KEY_NOTHING);
        if (c == KEY_F9){
          screen = 0;
          xt_par0(XT_CLEAR_SCREEN);
        }
        else if (c == KEY_F3){
        char str[80];
        for(i = 0; i < maxRecord; i++){
        	if(strcmp(catStorage[currentRecord].subject, dataStorage[i].subject) == 0 &&
        	   strcmp(catStorage[currentRecord].body, dataStorage[i].body) == 0 &&
        	   strcmp(catStorage[currentRecord].category, dataStorage[i].category) == 0 &&
        	   strcmp(catStorage[currentRecord].timedate, dataStorage[i].timedate) == 0){           //looks for corresponding record in the actual record list
        	  sprintf(str, "%d", i+1);
        	  break;
        	}
        }
        readmyStoreFromChildSOCKETS("delete", str, NULL, NULL, NULL);
        maxRecord--;
        screen = 0;
      }
    }
    if (screen == 3) break;
  }
  getkey_terminate();
  xt_par0(XT_CLEAR_SCREEN);
  xt_par0(XT_BG_DEFAULT);
  xt_par2(XT_SET_ROW_COL_POS,row=1,col=1);
  getkey_terminate();
  return 0;
}    
int main(int argc, char** argv) {
	int i, n;
	int* A;
	clock_t start, end;
	double elapsed_time, t1, t2;

	MPI_Init(NULL, NULL);
	int world_rank;
	MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
	int world_size;
	MPI_Comm_size(MPI_COMM_WORLD, &world_size);

	t1 = MPI_Wtime();
	if(world_rank == 0) {
		A = (int *)malloc(sizeof(int)*N);
		if (A == NULL) {
			printf("Fail to malloc\n");
			exit(0);
		}
		for (i=N-1; i>=0; i--)
			A[N-1-i] = i;
		
		if (isSorted(A, N))
		  printf("Array is sorted\n");
		else
		  printf("Array is NOT sorted\n");
	}

	//Scatter
	int *sub_A = (int *)malloc(sizeof(int) * N/world_size);
	assert(sub_A != NULL);


	MPI_Scatter(A, N/world_size, MPI_INT, sub_A, N/world_size, MPI_INT, 0, MPI_COMM_WORLD);


 // 	if(world_rank == 0){
	//  	printf("Rank: %d \n", world_rank);
	// 	printArray(&sub_A[0], 10);	
	// }

	bubbleSort(sub_A, N/world_size);
	printf("Rank: %d isSorted: %d\n", world_rank, isSorted(sub_A, N/world_size));
	// printArray(sub_A, N/world_size);

	//Gather
	
	int *result = NULL;
	if(world_rank == 0){
		result = (int *)malloc(sizeof(int) * N);
	}

	MPI_Gather(sub_A, N/world_size, MPI_INT, result, N/world_size, MPI_INT, 0, MPI_COMM_WORLD);

	if(world_rank == 0){
		printArray(&result[0], N);
		for(i = 0; i < world_size/2; i++){
			merge_swap(&result[N/world_size*i], &result[N/world_size*(world_size-i-1)], world_size);
		}
		printArray(&result[0], N);
	}

	
	
	// printArray(&result[0], N);

	
	// printArray(&result[N-10], 10);

	// printArray(&A[N-10], 10);
	
	// if (isSorted(A, N))
	//   printf("Array is sorted\n");
	// else
	//   printf("Array is NOT sorted\n");
	 
	// t2 = MPI_Wtime();
	// printf( "Elapsed time MPI_Wtime is %f\n", t2 - t1 ); 
	MPI_Finalize();
	return 0;
}
main(){
	int d,sear;
	struct node *head;
	struct node *second;
	head= (struct node *) malloc( sizeof(struct node) );
	second= (struct node *) malloc( sizeof(struct node) );
	head->data = 5; 
	head->next = second;	
	second->data=6;
	second->next = NULL;

	do
	{
	
		printf("\nMENU\n");
		printf("1. Add a new node to the start of the list\n");
		printf("2. Add a new node to the end of the list \n");
		printf("3. Display all of the nodes in the list \n");
		printf("4. Display the length of the list \n");
		printf("5. Search the linked list for a data value\n");
		printf("6. delete a node to the start of the list\n");
		printf("7. delete a node to the end of the list \n");
		printf("8. sort the list \n");
		printf("9. exit\n");
		printf("enter the option you want to choose");
		scanf("%d",&d);
	
		switch(d){
		case 1:
			addToStart(&head);
			break;
		case 2:
			addToEnd(head);
			break;
		case 3:
			DisplayAllNodes(head);
			break;
		case 4:
			DisplayLengthAllNodes(head);
			break;
		case 5:
			printf("enter the value you want to search\n");
			scanf("%d",&sear);
			searchList(head, sear);
			break;
		case 6:
			deleteFromStart(&head);
			break;
		case 7:
			deleteFromEnd(head);
			break;
		case 8:
			bubbleSort(head);
			break;
		case 9:
			exit(0);
			break;
		default:
			break;
		}
	system("cls");
	}while(d!=9);
	system("pause");
}
Exemple #14
0
int main() {

  //Print initial array
  printf("\n//=====Shuffled array===================//");
  setarray();
  printarray("Initial Array");

  //=====Simple sorts=====//
  printf("\n\n//=====Simple sorts====================//");
  //Insertion sort
  setarray();
  insertionSort(array,10);
  printarray("InsertionSort");
  //Selection sort
  setarray();
  selectionSort(array,10);
  printarray("SelectionSort");
  
  //=====Eficient Sorts=====//
  printf("\n\n//=====Eficient sorts==================//");
  //Mergesort
  setarray();
  mergeSort(array,0,9,10);
  printarray("MergeSort");
  //Heapsort
  setarray();
  heapSort(array,10);
  printarray("HeapSort");
  //Quicksort
  setarray();
  quickSort(array,0,9);
  printarray("QuickSort");
  
  //Bubble sort and variants
  printf("\n\n//=====Bubble sort and variants========//");
  //Bubblesort
  setarray();
  bubbleSort(array,10);
  printarray("BubbleSort");
  //Shellsort
  setarray();
  shellSort(array,10);
  printarray("ShellSort");
  //Combsort 
  setarray();
  combSort(array,10);
  printarray("CombSort");

  //Distribution sorts
  printf("\n\n//=====Distribution sorts==============//");
  //Countingsort
  setarray();
  countingSort(array, 10, 0, 99);
  printarray("CountingSort");   
  //Radixsort
  setarray();
  radixSort(array, 10);
  printarray("RadixSort");  

  //Other sorts
  printf("\n\n//=====Other sorts=====================//");
  //Gnomesort
  setarray();
  gnomeSort(array,10);
  printarray("GnomeSort");    
  //Cyclesort
  setarray();
  cycleSort(array,10);
  printarray("CycleSort");

  printf("\n\n");     
}
Exemple #15
0
int main(int argc, const char * argv[]) {
    for(int i=0;i<tam;i++){
        int v =rand()%1000;
        vetorQuick[i]=v;
        vetorSelDir[i]=v;
        vetorOrdDir[i]=v;
        vetorBubble[i]=v;
        vetorShell[i] = v;
    }
    showVetor(vetorQuick);
    int trocas[5]={0,0,0,0,0};
    clock_t tempoInicial, tempoFinal;
    double tempoGasto[5]={0,0,0,0,0};
    
    //quick
    tempoInicial = clock();
    quickSort(0, tam-1,trocas);
    tempoFinal = clock();
    
    tempoGasto[0] = (tempoFinal-tempoInicial)*1000/CLOCKS_PER_SEC;
    
    showVetor(vetorQuick);
    
    //selecao direta
    tempoInicial = clock();
    trocas[1]=selecaoDireta();
    tempoFinal = clock();
    
    tempoGasto[1] = (tempoFinal-tempoInicial)*1000/CLOCKS_PER_SEC;
    
    showVetor(vetorSelDir);
    
    //insercao direta
    tempoInicial = clock();
    trocas[2]=insercaoDireta();
    tempoFinal = clock();
    
    tempoGasto[2] = (tempoFinal-tempoInicial)*1000/CLOCKS_PER_SEC;
    
    showVetor(vetorOrdDir);
    
    //bubble
    tempoInicial = clock();
    trocas[3]=bubbleSort();
    tempoFinal = clock();
    
    tempoGasto[3] = (tempoFinal-tempoInicial)*1000/CLOCKS_PER_SEC;
    
    showVetor(vetorBubble);
    
    //Shell
    tempoInicial = clock();
    trocas[4]=shellSort();
    tempoFinal = clock();
    
    tempoGasto[4] = (tempoFinal-tempoInicial)*1000/CLOCKS_PER_SEC;
    
    showVetor(vetorShell);
  	

    printf("Ordenacao tempos e trocas:\nTempo em milisegundos para quick: %f e Quantidade de trocas: %d", tempoGasto[0],trocas[0]);
    printf("\nTempo em milisegundos para selecao direta: %f e Quantidade de trocas: %d", tempoGasto[1],trocas[1]);
    printf("\nTempo em milisegundos para insercao direta: %f e Quantidade de trocas: %d", tempoGasto[2],trocas[2]);
    printf("\nTempo em milisegundos para bubble: %f e Quantidade de trocas: %d", tempoGasto[3],trocas[3]);
    printf("\nTempo em milisegundos para shell: %f e Quantidade de trocas: %d", tempoGasto[4],trocas[4]);

    
    return 0;
}
Exemple #16
0
void test_sort_integer_data(){
	int data[5] = {5,2,8,1,3};
	int expected[5] = {1,2,3,5,8};
	bubbleSort(data, 5, sizeof(int), compareInt);
	ASSERT(0 == memcmp(data,expected,sizeof(expected)));
}
Exemple #17
0
int main()
{
	ADT indata[10][10];
    bubbleSort(indata[0], 10);
    return 0;
}
Exemple #18
0
void test_sort_float_data(){
	float data[5] = {5.2f,2.1f,8.4f,7.7f,8.2f};
	float expected[5] = {2.1f,5.2f,7.7f,8.2f,8.4f};
	bubbleSort(data, 5, sizeof(float), compareFloat);
	ASSERT(0 == memcmp(data,expected,sizeof(expected)));
}
Exemple #19
0
int main(int argc, char* argv[]) {

	if (argc < 7) {
		printf("Numero de argumentos insuficiente\n");
		printf("Uso: ./prog <tam_vetor> <chave> <tipo_busca>\n");
		printf("\t<tipo> = 1 sequencial, 2 binaria\n\n");
		printf("\t<sort> = 1 bubble, 2 insertion\n");
		printf("\t<tipo_vetor> = 1 aleatorio, 2 sequencial\n");
		printf("\t<tipo_op> = 1 leitura, 2 escrita\n");
		return 0;
	}	

	int n = atoi(argv[1]); // tamanho do vetor
	int chave = atoi(argv[2]); // numero a buscar nos dados
	int op = atoi(argv[3]);
	int sort = atoi(argv[4]);
	int tipovet = atoi(argv[5]);
	int rw = atoi(argv[6]);

	int * vet;
	if(tipovet == 1)
		vet = (int *)geraVetorAleatorio(n);
	else if (tipovet == 2)
		vet = (int *)geraVetorSequencial(n);
	printf("exemplos: %d, %d\n", vet[n-2], vet[n-1]);

	long int pos;

	clock_t c1;

	if (op == 1) {
		fprintf(stdout,"Realizando busca...\n");
		fflush(stdout);
		c1 = clock();
		pos = buscaSequencial(vet, n, chave);
		printf("busca: %.6fs\n", (float)(clock()-c1)/CLOCKS_PER_SEC);
	} else if (op == 2) {
		fprintf(stdout,"Ordenando...\n");
		fflush(stdout);
		c1 = clock();
		if(sort == 1)
			bubbleSort(vet, n); // nao usar - dica do Obama
		else if(sort == 2)
			insertionSort(vet, n);
		printf("sort: %.6fs\n", (float)(clock()-c1)/CLOCKS_PER_SEC);
		fprintf(stdout,"Realizando busca...\n");
		fflush(stdout);
		c1 = clock();
		pos = buscaBinaria(vet, 0, n-1, chave);
		printf("busca: %.6fs\n", (float)(clock()-c1)/CLOCKS_PER_SEC);
	}


	if (pos == -1) {
		printf("Valor nao encontrado\n\n");
	} else {
		printf("Valor encontrado na posicao: %ld\n\n", pos);
	}

	free(vet);


	return 0;
}
Exemple #20
0
/* Sort a hand of cards. */
void sortHand(Hand *hand, int handSize){
    bubbleSort((void **)(hand -> cards), handSize, (int(*)(void *, void *))compareCards);
}
Exemple #21
0
int main(int argc, char * argv[])
{
	clock_t time;
	std::vector<int> input;
	std::vector<int> output;

	//check for proper number of command-line arguments
	if(argc != 2)
	{
		std::cerr << "Incorrect number of arguments!" << std::endl;
		
		return 0;
	}

	//read values from input file and populate array
	std::ifstream file;
	std::string line;
	file.open(argv[1]);
	if(file.is_open())
	{
		while(getline(file, line))
		{
			input.push_back(atoi(line.c_str()));
		}
		file.close();
	}
	else
	{
		std::cerr << "Unable to open file!" << std::endl;

		return 0;
	}

	std::cout << "The vector has been populated." << std::endl;

	//perform insertion sort on the vector
	std::cout << "Insertion sort is beginning." << std::endl;
	time = clock();

	output = insertionSort(input);

	time = clock() - time;
	std::cout << "Insertion sort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform selection sort on the vector
	std::cout << "Selection sort is beginning." << std::endl;
	time = clock();

	output = selectionSort(input);

	time = clock() - time;
	std::cout << "Selection sort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform merge sort on the vector
	std::cout << "Merge sort is beginning." << std::endl;
	time = clock();

	output = mergeSort(input);

	time = clock() - time;
	std::cout << "Merge sort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform heapsort on the vector
	std::cout << "Heapsort is beginning." << std::endl;
	time = clock();

	output = heapSort(input);

	time = clock() - time;
	std::cout << "Heapsort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform quicksort on the vector
	std::cout << "Quicksort is beginning." << std::endl;
	time = clock();

	output = quickSort(input);

	time = clock() - time;
	std::cout << "Quicksort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform bubble sort on the vector
	std::cout << "Bubble sort is beginning." << std::endl;
	time = clock();

	output = bubbleSort(input);

	time = clock() - time;
	std::cout << "Bubble sort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	return 0;
}
Exemple #22
0
static void top_amp(struct PEXP *pexp, MODEL *model, int start, int end, int n_harm, int pred)
{
    int removed = 0, not_removed = 0;
    int top, i, j;
    struct AMPINDEX sorted[MAX_AMP];

    /* sort into ascending order of amplitude */

    printf("\n");
    for(i=start,j=0; i<end; i++,j++) {
	sorted[j].amp = model->A[i];
	sorted[j].index = i;
	printf("%f ", model->A[i]);
    }
    bubbleSort(sorted, end-start);

    printf("\n");
    for(j=0; j<n_harm; j++)
	printf("%d %f\n", j, sorted[j].amp);

    /* keep phase of top n_harm, predict others */

    for(i=start; i<end; i++) {		
	top = 0;
	for(j=0; j<n_harm; j++) {
	    if (model->A[i] == sorted[j].amp) {
		top = 1;
		assert(i == sorted[j].index);
	    }
	}
	
	#define ALTTOP
	#ifdef ALTTOP
	model->phi[i] = 0.0; /* make sure */
	if (top) {
	    model->phi[i] = i*pexp->phi1;
	    removed++;
	}
	else {
	    model->phi[i] = PI*(1.0 - 2.0*(float)rand()/RAND_MAX); // note: try rand for higher harms
	    removed++;
	}
	#else
	if (!top) {
	    model->phi[i] = 0.0; /* make sure */
	    if (pred)  {
		//model->phi[i] = pexp->phi_prev[i] + i*N*(model->Wo + pexp->Wo_prev)/2.0;
		model->phi[i] = i*model->phi[1];
	    }
	    else
		model->phi[i] = PI*(1.0 - 2.0*(float)rand()/RAND_MAX); // note: try rand for higher harms
	    removed++;
	}
	else {
	    /* need to make this work thru budget of bits */
	    quant_phase(&model->phi[i], -PI, PI, 3);	    
	    not_removed++;
	}
	#endif
    }
    printf("dim: %d rem %d not_rem %d\n", end-start, removed, not_removed);
	    
}
Exemple #23
0
/**
 * Sorts array of n values.
 */
void sort(int values[], int n)
{
    bubbleSort(values, n);
    return;
}
int main(int argc, char *argv[]){
	if(argc == 1){
		printf("Very Few Arguments\n");
		printf("File Name Missing\n");
		exit(1);
	}

	list *l = (list *)malloc(sizeof(list));
	init(l);
	path *paths;
	FILE *fp;
	int i, j, flag = 0, SIZE = 1024, USIZE = 1024, uCount, uFlag = 0, uFlag_1 = 0, uTmp;
	char zipFileName[32] = "", *buffer, *binary, *output, *huffList, character, dflag, cnt, *saket;
	for(i = 0; argv[1][i] != '\0'; i++){
		zipFileName[i] = argv[1][i];
	}
	zipFileName[i++] = '.';
	zipFileName[i++] = 's';
	zipFileName[i++] = 'a';
	zipFileName[i++] = 'k';

	fp = fopen(argv[1], "r");
	if(!fp){
		printf("File Doesn't Exist\n");
		exit(2);
	}

	buffer = (char *)malloc(SIZE * sizeof(char));
	i = 0;
	while((character = getc(fp)) != EOF){
		buffer[i] = character;
		if(i >= (SIZE - 1)){
			SIZE *= 2;
			buffer = (char *)realloc(buffer, SIZE);
		}
		if(flag == 0){
			append(l, character);
			flag = 1;
		}
		else
			searchAndAdd(l, character);
		i++;
	}
	buffer[i] = '\0';
	fclose(fp);

	bubbleSort(l); //Initial Sorting According to Weight.

	l = huffmanTree(l);

	assignPath(l);

	paths = (path *)malloc(l->cnt * sizeof(path));
	storePath(l->head, paths);

	huffList = (char *)malloc(SIZE * sizeof(char));
	storeHuffList(huffList, paths, l->cnt);

	binary = (char *)malloc(SIZE * sizeof(char));
	binaryConversion(buffer, binary, paths);
	printf("%s\n", binary);
	i = strlen(binary);
	printf("%d\n", i);
	free(buffer);
	free(paths);

	appendRedundantBits(binary);
	printf("%s\n", binary);

	output = (char *)malloc(SIZE * sizeof(char));
	binToAscii(binary, output);
	printf("%s\n", output);

	free(binary);

	dflag = (char)252; //11111100
	cnt = (char)l->cnt;//nodeCount
	fp = fopen(zipFileName, "w+");
	fprintf(fp, "%c", cnt);
	fprintf(fp, "%s", huffList);
	fprintf(fp, "%c", dflag);
	fprintf(fp, "%s", output);
	free(huffList);
	free(output);
	fclose(fp);

	printf("\nCompressed\n\t-------------------------------------------------------------------------------------------------------------\n");

	return 0;
}
Exemple #25
0
int main(void) {

	setvbuf(stdout, NULL, _IONBF, 0);

	Header head;

	head.head = NULL;
	head.tail = NULL;
	head.nodeCount = 0;

	int menu = 0, list = 0;

	do {

		do {
			system("cls");
			printf("\n Manipular qual lista.\n");
			printf("1 - Encadeada.\n");
			printf("2 - Sequencial.\n");

			scanf("%d", &list);

			system("cls");
		} while (list != 1 && list != 2);

		system("cls");
		printf("\n Digite o numero da opcao desejada.\n");
		printf("1 - Inserir elemento no final da lista.\n");
		printf("2 - Inserir elemento no inicio da lista.\n");
		printf("3 - Remover elemento a partir de um valor.\n");
		printf("4 - Imprimir a lista.\n");
		printf("5 - Inserir na posicao N.\n");
		printf("6 - Remover ultimo da lista.\n");
		printf("7 - Remover primeiro da lista.\n");
		printf("8 - Remover elemento na posicao N.\n");
		printf("9 - Carregar lista do arquivo.\n");
		printf("10 - Salvar lista atual em arquivo.\n");
		printf("11 - Inserction.\n");
		printf("12 - Selection.\n");
		printf("13 - Bubble.\n");
		printf("14 - Shell.\n");
		printf("15 - Quick.\n");
		printf("16 - Merge.\n");
		printf("17 - Busca Binaria.\n");
		printf("18 - Busca Seq.\n");

		printf("20 - Sair.\n");

		scanf("%d", &menu);

		system("cls");

		switch (menu) {
		case 1:
			if (list == 1) {
				insertNodeAtTheEnd(&head, getValue(), 1);
				reference(&head);
			} else {
				insertSeqAtTheEnd(getValue(), 1);
			}
			break;
		case 2:
			if (list == 1) {
				insertNodeAtStart(&head, getValue(), 1);
				reference(&head);
			} else {
				insertSeqAtStart(getValue(), 1);
			}
			break;
		case 3:
			if (list == 1) {
				deleteNodeByValue(&head);
				reference(&head);
			} else {
				deleteSeqByValue();
			}
			break;
		case 4:
			if (list == 1) {
				printList(&head);
			} else {
				printSeq();
			}
			break;
		case 5:
			if (list == 1) {
				insertAtN(&head, getValue(), getPosIns(&head));
				reference(&head);
			} else {
				insertSeqAtN(getValue(), getPosSeqIns());
			}
			break;
		case 6:
			if (list == 1) {
				deleteLastNode(&head, 1);
				reference(&head);
			} else {
				deleteLastSeq(1);
			}
			break;
		case 7:
			if (list == 1) {
				deleteFirstNode(&head, 1);
				reference(&head);
			} else {
				deleteFirstSeq(1);
			}
			break;
		case 8:
			if (list == 1) {
				deleteNodeAtN(&head, getPosDel(&head));
				reference(&head);
			} else {
				deleteSeqAtN(getPosSeqDel(), 1);
			}
			break;
		case 9:
			listOptions(&head, list);
			break;
		case 10:
			if (list == 1) {
				writeLinkedList(&head);
			} else {
				writeSequentialList();
			}
			break;
		case 11:
			if (list == 1) {
				linkedInserctionSort(&head);
			} else {
				inserctionSort();
			}
			break;
		case 12:
			if (list == 1) {
				linkedSelectionSort(&head);
			} else {
				selectionSort();
			}
			;
			break;
		case 13:
			if (list == 1) {
				linkedBubbleSort(&head);
			} else {
				bubbleSort();
			}
			break;
		case 14:
			if (list == 1) {
				linkedShellSort(&head);
			} else {
				shellSort();
			}
			break;
		case 15:
			if (list == 1) {
				linkedCallQuickSort(&head);
			} else {
				callQuickSort();
			}
			break;
		case 16:
			if (list == 1) {
				linkedCallMergeSort(head.nodeCount);
			} else {
				callMergeSort();
			}
			break;
		case 17:
			if (list == 1) {
				linkedCallBynarySearch(&head);
			} else {
				callBynarySearch();
			}
			break;
		case 18:
			if (list == 1) {
				searchNodeByValue(&head);
			} else {
				searchByValue();
			}
			break;
		}

	} while (menu != 20);

	wipeList(&head);

	return EXIT_SUCCESS;
}
Exemple #26
0
int main()
{
    //variable declrations
    int myArray[50], myArray2[] = {1, 2, 3, 4, 5}, myArray3[] = {1, 2, 3, 4, 5};
    int index, searchResults, key;


    //testing fillArray
    fillArray(myArray, 50, 1000);
    //testing printNperline()
    printf("Before sort printing 10 per line\n");
    printNperline(myArray, 50, 10);

    printf("\n");
    printf("Before sort printing 4 per line\n");
    printNperline(myArray, 50, 4);

    printf("\n");
    printf("Before sort printing 6 per line\n");
    printNperline(myArray, 50, 6);

    //testing bubble sort on myArray
    bubbleSort(myArray, 50);

    //printing myArray after sort
    printf("\n");
    printf("After sort printing 6 per line\n");
    printNperline(myArray, 50, 6);

    printf("\n");
    printf("After sort printing 15 per line\n");
    printNperline(myArray, 50, 15);

    printf("\n");
    printf("After sort printing 11 per line\n");
    printNperline(myArray, 50, 11);

    //testing linear search
    printf("\n");
    printf("Testing linear search for 82\n");
    key = 82;
    searchResults = linearSearch(myArray, 50, key);

    if(searchResults >= 0)
        printf("The key value %d was found in myArray at position %d\n", key, searchResults);
    else
        printf("The key value %d was not found in myArray\n", key);

    printf("\n");
    printf("Testing linear search for %d which is the last element in the array\n", myArray[49]);
    key = myArray[49];
    searchResults = linearSearch(myArray, 50, key);

    if(searchResults >= 0)
        printf("The key value %d was found in myArray at position %d\n", key, searchResults);
    else
        printf("The key value %d was not found in myArray\n", key);

    printf("\n");
    printf("Testing linear search for %d which is the first element in the array\n", myArray[0]);
    key = myArray[0];
    searchResults = linearSearch(myArray, 50, key);

    if(searchResults >= 0)
        printf("The key value %d was found in myArray at position %d\n", key, searchResults);
    else
        printf("The key value %d was not found in myArray\n", key);

    //testing shiftElements
    printf("\n");
    printf("Shifting the elements in the array right 6 elements\n");
    shiftElements(myArray, 50, 6);
    printNperline(myArray, 50, 10);

    printf("\n");
    printf("Shifting the elements in the array left 4 elements\n");
    shiftElements(myArray, 50, -4);
    printNperline(myArray, 50, 10);

}
int main(int argc, char** argv) {
	int i, n;
	int* A, *temp, *temp2;
	clock_t start, end;
	double elapsed_time, t1, t2;

	MPI_Init(NULL, NULL);
// Find out rank, size
	  int world_rank;
	  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
	  int world_size;
	  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
	
	int elements_per_proc = N/world_size;

	t1 = MPI_Wtime();
	A = (int *)malloc(sizeof(int)*N);
	temp = (int *)malloc(sizeof(int)*N);
	temp2 = (int *)malloc(sizeof(int)*N);
	if (A == NULL) {
		printf("Fail to malloc\n");
		exit(1);
	}
//create an array of Numbers if process is 0
if (world_rank == 0) {
  for (i=N-1; i>=0; i--)
		A[N-1-i] = i;
}

	
// Create a buffer that will hold a subset of the numbers
 int *sub_bubble_nums = malloc(sizeof(int) * elements_per_proc);

// Scatter the random numbers to all processes
MPI_Scatter(A, elements_per_proc, MPI_INT, sub_bubble_nums,
            elements_per_proc, MPI_INT, 0, MPI_COMM_WORLD);

// Sort the sub array with bubble sort
bubbleSort(sub_bubble_nums, elements_per_proc);
// Gather all partial averages down to the root process

MPI_Gather(sub_bubble_nums, elements_per_proc, MPI_INT, temp, elements_per_proc, MPI_INT, 0,
           MPI_COMM_WORLD);

// Compute the total average of all numbers.
if (world_rank == 0) {
mergeSort(N,temp,temp2);
//bubbleSort(temp,N);
t2 = MPI_Wtime();
printf( "Elapsed time MPI_Wtime is %f\n", t2 - t1 );
}

	if (isSorted(temp, N))
	  printf("%i is sorted\n",world_rank);
	else
	  printf("Array is NOT sorted\n");
	
	 

	MPI_Finalize();
	return 0;
}
Exemple #28
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qreal ax = -5, bx = 5;
    TVect b;
    TVect testVector = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9};
    char *itemMenu[] =
    {
        "A - Загрузить тестовый вектор",
        "B - Загрузить вектор с помощью генератора случайных чисел",
        "C - Сортировать вектор с помощью метода выбора",
        "D - Сортировать вектор с помощью метода пузырька",
        "E - Сортировать вектор с помощью метода вставки",
        "F - Сохранить вектор в файле",
        "G - Считать вектор из файла",
        "X - Выйти из программы"
    };
    char *hotKeys = "ABCDEFG";
    char selectedBranch;
    initRandom();
    while (true)
    {
        selectedBranch = menu(itemMenu, hotKeys);
        switch (selectedBranch) {
        case 'A':
            cout << "Загрузка тестового вектора" << endl;
            loadTestVector(b, testVector);
            printArray(b);
            break;
        case 'B':
            cout << "Загрузка вектора с помощью генератора случайных чисел" << endl;
            fillArrayRand(b, ax, bx);
            printArray(b);
            break;
        case 'C':
            cout << "Сортировать вектор с помощью метода выбора" << endl;
            cout << "Вектор до сортировки" << endl;
            printArray(b);
            selectionSort(b);
            cout << "Вектор после сортировки" << endl;
            printArray(b);
            break;
        case 'D':
            cout << "Сортировать вектор с помощью метода пузырька" << endl;
            cout << "Вектор до сортировки" << endl;
            printArray(b);
            bubbleSort(b);
            cout << "Вектор после сортировки" << endl;
            printArray(b);

            break;
        case 'E':
            cout << "Сортировать вектор с помощью метода вставки" << endl;
            cout << "Вектор до сортировки" << endl;
            printArray(b);
            insertionSort(b, N);
            cout << "Вектор после сортировки" << endl;
            printArray(b);
            break;
        case 'F':
            cout << "Сохранить вектор в файле" << endl;
            cout << "Введите имя файла:";
        {
            string fileName = "";
            cin >> fileName;
            char *cstr = new char[fileName.length() + 1];
            strcpy(cstr, fileName.c_str());
            if (writeVectFile(cstr, b))
            {
                cout << "Вектор сохранён в файле"<< "\n";
            }
            else
            {
                cout << "При сохранении произошла ошибка\n";
            }
            delete [] cstr;
        }
            break;
        case 'G':
            cout << "Считать вектор из файла" << endl;
            cout << "Введите имя файла:";
        {
            string fileName = "";
            cin >> fileName;
            if (readVectFile(fileName,b))
            {
                cout << "Вектор прочитан из файла"<< "\n";
            }
            else
            {
                cout << "При считывании произошла ошибка\n";
            }
        }

            break;
        default:
            break;
        }
    }
    initRandom();
    fillArrayRand(b, ax, bx);
    printArray(b);
    //selectionSort(b);
    bubbleSort(b);
    cout<<"After selection sorting"<<endl;
    printArray(b);
    cout<<"Insertion sorting"<<endl;
    fillArrayRand(b, ax, bx);
    cout<<"Before:"<<endl;
    printArray(b);
    cout<<"After:"<<endl;
    insertionSort(b, N);
    printArray(b);
    writeVectFile("/home/ametovii/Temp/vect.txt", b);
    return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Interface function
////////////////////////////////////////////////////////////////////////////////
extern "C" void mergeSortHost(
    uint *dstKey,
    uint *dstVal,
    uint *bufKey,
    uint *bufVal,
    uint *srcKey,
    uint *srcVal,
    uint N,
    uint sortDir
){
    uint *ikey, *ival, *okey, *oval;
    uint stageCount = 0;
    for(uint stride = SHARED_SIZE_LIMIT; stride < N; stride <<= 1, stageCount++);
    if(stageCount & 1){
        ikey = bufKey;
        ival = bufVal;
        okey = dstKey;
        oval = dstVal;
    }else{
        ikey = dstKey;
        ival = dstVal;
        okey = bufKey;
        oval = bufVal;
    }

    printf("Bottom-level sort...\n");
        memcpy(ikey, srcKey, N * sizeof(uint));
        memcpy(ival, srcVal, N * sizeof(uint));
        for(uint pos = 0; pos < N; pos += SHARED_SIZE_LIMIT)
           bubbleSort(ikey + pos, ival + pos, umin(SHARED_SIZE_LIMIT, N - pos), sortDir);

    printf("Merge...\n");
        uint  *ranksA = (uint *)malloc( getSampleCount(N) * sizeof(uint) );
        uint  *ranksB = (uint *)malloc( getSampleCount(N) * sizeof(uint) );
        uint *limitsA = (uint *)malloc( getSampleCount(N) * sizeof(uint) );
        uint *limitsB = (uint *)malloc( getSampleCount(N) * sizeof(uint) );
        memset(ranksA,  0xFF, getSampleCount(N) * sizeof(uint));
        memset(ranksB,  0xFF, getSampleCount(N) * sizeof(uint));
        memset(limitsA, 0xFF, getSampleCount(N) * sizeof(uint));
        memset(limitsB, 0xFF, getSampleCount(N) * sizeof(uint));

        for(uint stride = SHARED_SIZE_LIMIT; stride < N; stride <<= 1){
            uint lastSegmentElements = N % (2 * stride);

            //Find sample ranks and prepare for limiters merge
            generateSampleRanks(ranksA, ranksB, ikey, stride, N, sortDir);

            //Merge ranks and indices
            mergeRanksAndIndices(limitsA, ranksA, stride, N);
            mergeRanksAndIndices(limitsB, ranksB, stride, N);

            //Merge elementary intervals
            mergeElementaryIntervals(okey, oval, ikey, ival, limitsA, limitsB, stride, N, sortDir);

            if( lastSegmentElements <= stride ) {
                //Last merge segment consists of a single array which just needs to be passed through
                memcpy(okey + (N - lastSegmentElements), ikey + (N - lastSegmentElements), lastSegmentElements * sizeof(uint));
                memcpy(oval + (N - lastSegmentElements), ival + (N - lastSegmentElements), lastSegmentElements * sizeof(uint));
            }

            uint *t;
            t = ikey; ikey = okey; okey = t;
            t = ival; ival = oval; oval = t;
        }

        free(limitsB);
        free(limitsA);
        free(ranksB);
        free(ranksA);
}