Example #1
0
main()
{
	SV a[100];
	int n=0;
	nhapSV(a, n);
	printf("\nDanh sach ban dau: \n");
	inSV(a, n);
	insertionsort(a, n, ssMSSV);
	printf("\nDay sap xep theo Ma so: \n");
	inSV(a, n);
	insertionsort(a, n, ssdiem);
	printf("\nDay sap xep theo diem giam dan: \n");
	inSV(a, n);
	getch();
}
Example #2
0
// Cut2c does 2-partitioning with one pivot.
// Cut2c invokes dflgm when trouble is encountered.
void cut2c(void **A, int N, int M, int depthLimit, int (*compareXY)()) {
  int L;
 Start:
  L = M - N + 1;
  if ( L <= 1 ) return;

  // /*
  if ( L < 8 ) { // insertionsort
    insertionsort(A, N, M, compareXY);
    return;
  }
  //  */

  if ( depthLimit <= 0 ) {
    heapc(A, N, M, compareXY);
    return;
  }
  depthLimit--;

  // /*
  if ( L < cut2Limit ) { 
    // This alternative over esaping to quicksort0c reduced 1/2% comparions
    int middlex = N + (L>>1); // N + L/2;
    int p0 = middlex;
    if ( 7 < L ) {
      int pn = N;
      int pm = M;
      if ( 51 < L ) {	
	int d = (L-2)>>3; // L/8;
	pn = med(A, pn, pn + d, pn + 2 * d, compareXY);
	p0 = med(A, p0 - d, p0, p0 + d, compareXY);
	pm = med(A, pm - 2 * d, pm - d, pm, compareXY);
      }
Example #3
0
void
kms_kv_list_sort (kms_kv_list_t *lst, int (*cmp) (const void *, const void *))
{
   /* A stable sort is required to sort headers when creating canonical
    * requests. qsort is not stable. */
   insertionsort (
      (unsigned char *) (lst->kvs), lst->len, sizeof (kms_kv_t), cmp);
}
Example #4
0
int main(){
	int arrsize = 10;
	int array[] = {6,7,5,4,3,8,9,1,2,0};

	print_array(array, arrsize);
	insertionsort(array, arrsize);
	print_array(array, arrsize);
}
Example #5
0
void * insertionsort_thread (void * arg)
{
    targ_t * targ = (targ_t*)arg;

    // Sort the data
    insertionsort(targ->data, targ->length);

    return (void*)(999);
}
Example #6
0
int main()
{
	int i,n;
	printf("输入随机数个数n:");
	scanf("%d",&n);

	printf("需要在屏幕上显示生成的元素吗?输入y显示,n不显示(y/n):");
	char flag;
	scanf("%s",&flag);
	if(flag == 'y')
	{
		printf("以下是系统随机生成的%d个元素:",n);
	}
	//文件操作
	FILE *fp;
	fp = fopen("insertionsort.txt","w");
	if(!fp)
	{
		printf("Error to open file to write");
		return 0;
	}
	fprintf(fp,"产生随机数个数%d\n",n);

	//产生随机数
	int* a= (int*)malloc((n)*sizeof(int));
	srand((int)time(0));
    fprintf(fp,"产生随机数列:");
	for(i=0;i<n;i++){
		a[i]=rand();
		if(flag == 'y')
		{
			printf("%d ",a[i]);
		}
		fprintf(fp,"%d ",a[i]);
	}
	
	printf("\n");
	int result;
	clock_t start,finish;
	double duration;
	
	start = clock();
	result = insertionsort(a,n);
	finish = clock();
	duration = (double)((finish - start)*1.0/CLOCKS_PER_SEC) ;
	printf("插入排序为:\n");
	fprintf(fp,"\n\n插入排序结果:");
	for(i=0;i<n;i++){
		
			printf("%d ",a[i]);
			fprintf(fp,"%d ",a[i]);
	}
	fclose(fp);
	printf("\n运行时间为:%lf秒\n",duration);
	delete[]a;
	return 0;
}
int main()
{
	int arr[]={32,11,25,6,77,2};
	int n=sizeof(arr)/sizeof(arr[0]);
	printarray(arr,n);
	insertionsort(arr,n);
	printarray(arr,n);
	return 0;
}
Example #8
0
int main(int argc, char* argv[])
{
	char test[] = "pfannekuchen";
	int len = sizeof(test) / sizeof(char);

	printf("Unsortiert:    %s\n",test);
	insertionsort(test,len);
	printf("InsertionSort: %s\n",test);
	return 0;
}
Example #9
0
// Quicksort function for invoking quicksort0c.
void quicksort0(int N, int M) {
  int L = M - N;
  if ( L <= 0 ) return;
  // printf("quicksort0 %d %d \n", N, M);
  if ( L <= 10 ) { 
    insertionsort(N, M);
    return;
  }
  int depthLimit = 2 * floor(log(L));
  quicksort0c(N, M, depthLimit);
} // end quicksort0
Example #10
0
void shellSort(Element A[], int n)
{
    int m;

    for(m = n/2; m > 0; m /= 2)
    {
        for(int i = 0; i < m; i++)
	{
            insertionsort(&(A[i]), n-i, m);
	}
    }
}
Example #11
0
void shellSort(Element A[], int n)
{
    int m;

    for(m = n/2; m > 0; m /= 2)
    {
#pragma omp parallel for shared(A,m,n) default(none)
        for(int i = 0; i < m; i++)
	{
            insertionsort(&(A[i]), n-i, m);
	}
    }
}
Example #12
0
int main(){
	srand(time(NULL)); //Damit rand() nicht immer gleiche Folgen ausgibt
	clock_t begin, end;
	int size;
	
	//Aufgabe 3b)
	//Sortieralgorithmen bereits nach ihrer Laufzeit sortiert.
	printf("Welche Laenge(int) soll das Array haben?\n>");
	scanf("%d", &size);
	printf("Eingegebene Arraylaenge: %d\nAuflistung der Laufzeiten:\n", size);
	
	double* arr = malloc(size * sizeof(double));
	double* arrCopy = malloc(size * sizeof(double));
	for(int i = 0; i < size; i++){
		arr[i] = randBet(-1000, 1000);
		arrCopy[i] = arr[i];
	}
	begin = clock();
	quicksort(arrCopy, size);
	end = clock();
	printf("quicksort: %d\n",end-begin);
	
	CopyFirst(arr, arrCopy, size);
	begin = clock();
	mergesort(arrCopy, size);
	end = clock();
	printf("mergesort: %d\n",end-begin);
	
	CopyFirst(arr, arrCopy, size);
	begin = clock();
	selectionsort(arrCopy, size);
	end = clock();
	printf("Selektionsort: %d\n",end-begin);
	
	CopyFirst(arr, arrCopy, size);
	begin = clock();
	insertionsort(arrCopy, size);
	end = clock();
	printf("Insertionsort: %d\n",end-begin);
	
	CopyFirst(arr, arrCopy, size);
	begin = clock();
	bubblesort(arrCopy, size);
	end = clock();
	printf("Bubblesort: %d\n",end-begin);

	free(arr);
	free(arrCopy);
	
	return 0;
}
Example #13
0
/*
 * This funtion has been written to easen the distance calculation process for $
 * It basically takes in the array and a Number N. It then sums the N least numbers
 * int the array and gives the sum as output 
 */
int dist_calc(int* Arr, int N)
{
    int i;
    int temp[60];
    for(i=0;Arr[i]!= -10;i++);
        temp[i] = Arr[i];
    
// Using insertionsort as it works best on already sorted arrays    
    insertionsort(i,temp);
    int sum =0;
    for(i=0;i<N;i++)
        sum = sum + temp[i];
    return sum;    
}
Example #14
0
int sort_file(const char* filename) {
    FILE *fp = fopen(filename, "r");
    if(fp == NULL) {
        return EXIT_FAILURE;
    }

    int size = 0; // smells, but what else? struct?
    int *numbers = read_file(fp, &size); // write size to *size
    insertionsort(size, numbers);
    printArr(size, numbers);
    write_file(filename, size, numbers);
    free(numbers);
    fclose(fp);
}
Example #15
0
File: main.c Project: f2008700/BITS
int main()
{
	int i,N;
	List A={55, 44, 77, 88, 22, 33, 99, 11, 66};
	N=9;
	printf("\nThe Array before sorting\n");
	for(i=0;i<N;i++)
		printf("%d\t",A[i]);
	insertionsort(A,N);
	printf("\n\nThe Array After sorting\n");
	for(i=0;i<N;i++)
		printf("%d\t",A[i]);
	return 0;
}
Example #16
0
void		aff_opt_1(void)
{
      int	*tab;

      tab = create_tab(n);
      fill_tab(&tab);
      printf("\n%s - Tableau Initial :\n%s\t", COLOR, NONE);
      aff_tab(tab);
      printf("%s - Tri rapide :\n%s\t", COLOR, NONE);
      aff_tab(quicksort(tab, 0, n));
      printf("\n");
      free(tab);

      tab = create_tab(n);
      fill_tab(&tab);
      printf("%s - Tableau Initial :\n%s\t", COLOR, NONE);
      aff_tab(tab);
      printf("%s - Tri par fusion :\n%s\t", COLOR, NONE);
      aff_tab(fusionsort(tab, 0, n));
      printf("\n");
      free(tab);

      tab = create_tab(n);
      fill_tab(&tab);
      printf("%s - Tableau Initial :\n%s\t", COLOR, NONE);
      aff_tab(tab);
      printf("%s - Tri bulle :\n%s\t", COLOR, NONE);
      aff_tab(bubble_sort(tab));
      printf("\n");
      free(tab);

      tab = create_tab(n);
      fill_tab(&tab);
      printf("%s - Tableau Initial :\n%s\t", COLOR, NONE);
      aff_tab(tab);
      printf("%s - Tri selection :\n%s\t", COLOR, NONE);
      aff_tab(selectionsort(tab));
      printf("\n");
      free(tab);

      tab = create_tab(n);
      fill_tab(&tab);
      printf("%s - Tableau Initial :\n%s\t", COLOR, NONE);
      aff_tab(tab);
      printf("%s - Tri insertion :\n%s\t", COLOR, NONE);
      aff_tab(insertionsort(tab));
      printf("\n");
      free(tab);
}
int main(){
	
	int arr[] = {5,3,5,4,1,2,90,100,11,1,0,-12};
	int size;

	size = sizeof(arr)/sizeof(arr[0]);

	printf("\nBefore Sorted\n");
	printarray(arr,size);
	insertionsort(arr,size);
	printf("\nAfter Sorted\n");
	printarray(arr,size);
	printf("\n");

}
Example #18
0
int main() {
    //размер массива
    int n;
    scanf("%d", &n);
    int a[n], i = 0;
    
    for (i = 0; i < n; i++) scanf("%d", &a[i]);

    //указатель для передачи массива функции
    int *A = a;
    if (n <= 5) insertionsort (A, n);
    else MergeSort(A, n);
    
    for (i = 0; i < n; i++) printf("%d ", a[i]);
}
Example #19
0
int main()
{
    int *sortingarray;
    int i,a,b,c;
    srand(time(NULL)*time(NULL));
    printf("Enter size of array: valid values 1-35533\n");
    scanf("%d",&a);
    sortingarray=(int *) malloc(a*sizeof(int));
    a=a-1;
    arraygenerate(sortingarray,&a);
    i=0;
    printf("What sorting mechanism?\n Bubble/shaker -1\nSelection -2\nInsertion -3");
    scanf("%d",&c);
    if(c==1){
    bubblesort(sortingarray,&a);}
    if(c==2){selectionsort(sortingarray,&a);}
    if(c==3){insertionsort(sortingarray,&a);}
    while(i<=a){printf("%d\t",sortingarray[i]);i++;}
    nickname();
    return 0;
}
Example #20
0
int start(int N)                           // overhead!
{
    int i,j;

    // read N numbers
    for(i = 0; i < N; i++)
    {
       list[i] = read_uint32("inpipe");
    }
    
    insertionsort(0,N-1,list);
        

    // write out the sorted list        
    for(j = 0; j < N; j++)
    {
	write_uint32("outpipe",list[j]);
    }

    return 0;       // successful termination.
}
Example #21
0
void sort()
{
int z=1,choice,a;
 while(z==1) 
    { 
      printf("\n\n****************************************SORTING $ SEARCHING MODULE*****************************\n\n");       
 printf("Enter 1 for binary search\nEnter 2 for bubble sort\n Enter 3 for insertion sort\n Enter 4 for selection sort \n Enter 5 for quick sort:"); 
            scanf("%d",&choice); 
        
    
    switch(choice) 
    { 
        case 1: 
           a=binarysearch(); 
            break; 
            
        case 2: 
           bubblesort();  
            break; 
       case 3: 
            a=insertionsort();
            break;
          case 4: 
           selectionsort(); 
            break; 
           case 5: 
           quicksort(); 
            break; 
        default: 
            printf("\nERROR"); 
            
    } 
        
        
    printf("PRESS 1 for continue 0 for exit"); 
scanf("%d",&z); 
    } 


}
Example #22
0
int main()
{
    
    int n = 6;
    void **list;
    for( int i = 0 ; i < n ; i++ )
    {    
         int *x=(int*) malloc (sizeof( int ) ) ;
         scanf("%d" , x );
         *(list + i ) = x ;
    }
    
    insertionsort(list , n );
    
    printf("x");
    
    disp(list , n );
    
    
    printf("x");
    
    getch();
} 
/* FBP_voc algorithm */
void FBP_voc(double ALPHA, double BETA, int W, int J, int D, int NN, int OUTPUT, int nzmax, 
	double *sr, mwIndex *ir, mwIndex *jc, double *phi, double *theta, double *mu, double threshold, int startcond) 
{
	int wi, di, i, j, k, topic, iter, rp, temp, ii;
	int *order, *indx_r;
	double mutot, totprob, xi, xitot, perp, trap = 1e-6;
	double JALPHA = (double) (J*ALPHA), WBETA = (double) (W*BETA);
	double *phitot, *thetad, *r, *munew;

	phitot = dvec(J);
	thetad = dvec(D);
	order = ivec(W);
	indx_r = ivec(J*W);
	munew = dvec(J);
	r = dvec(J*W);

	/* phitot */
	for (wi=0; wi<W; wi++) {
		for (j=0; j<J; j++) {
			phitot[j] += phi[wi*J + j];
		}
	}

	if (startcond == 1) {
		/* start from previously saved state */
		for (wi=0; wi<W; wi++) {
			for (i=jc[wi]; i<jc[wi + 1]; i++) {
				di = (int) ir[i];
				xi = sr[i];
				xitot += xi;
				thetad[di] += xi;
				for (j=0; j<J; j++) {
					theta[di*J + j] += xi*mu[i*J + j]; // increment theta count matrix	
				}
			}
		}
	}

	if (startcond == 0) {
		/* random initialization */
		for (wi=0; wi<W; wi++) {
			for (i=jc[wi]; i<jc[wi + 1]; i++) {
				di = (int) ir[i];
				xi = sr[i];
				thetad[di] += xi;
				xitot += xi;
				// pick a random topic 0..J-1
				topic = (int) (J*drand());
				mu[i*J + topic] = 1.0; // assign this word token to this topic
				theta[di*J + topic] += xi; // increment theta count matrix
			}
		}
	}

	/* Determine random order */
	for (i=0; i<W; i++) order[i] = i; // fill with increasing series
	for (i=0; i<(W-1); i++) {
		// pick a random integer between i and D
		rp = i + (int) ((W-i)*drand());
		// switch contents on position i and position rp
		temp = order[rp];
		order[rp] = order[i];
		order[i] = temp;
	}

	for (iter=0; iter<NN; iter++) {

		if (OUTPUT >= 1) {
			if (((iter % 10)==0) && (iter != 0)) {
				/* calculate perplexity */
				perp = 0.0;
				for (wi=0; wi<W; wi++) {
					for (i=jc[wi]; i<jc[wi + 1]; i++) {
						di = (int) ir[i];
						xi = sr[i];
						mutot = 0.0;
						for (j=0; j<J; j++) {
							mutot += (phi[wi*J + j] + BETA)/(phitot[j] + WBETA)*
								(theta[di*J + j] + ALPHA)/(thetad[di] + JALPHA);
						}
						perp -= (log(mutot)*xi);
					}
				}
				mexPrintf("\tIteration %d of %d:\t%f\n", iter, NN, exp(perp/xitot));
				if ((iter % 10)==0) mexEvalString("drawnow;");
			}
		}

		/* passing message mu */
		
		/* iteration 0 */
		if (iter == 0) {
			for (ii=0; ii<W; ii++) {
				wi = (int) order[ii];
				for (i=jc[wi]; i<jc[wi + 1]; i++) {
					di = (int) ir[i];
					xi = sr[i];
					mutot = 0;
					for (j=0; j<J; j++) {
						theta[di*J + j] -= xi*mu[i*J + j];	
						munew[j] = (phi[wi*J + j] + BETA)/(phitot[j] + WBETA)*(theta[di*J + j] + ALPHA);
						mutot += munew[j];
					}
					for (j=0; j<J; j++) {
						munew[j] /= mutot;
						r[wi*J + j] += xi*fabs(munew[j] - mu[i*J + j]);
						mu[i*J + j] = munew[j];
						theta[di*J + j] += xi*mu[i*J + j];
					}
				}
				dsort(J, r + wi*J, -1, indx_r + wi*J);
			}
		} else { /* iteration > 0 */
			for (ii=0; ii<W; ii++) {
				wi = (int) order[ii];
				for (j=0; j < (int) (J*threshold); j++) {
					k = (int) indx_r[wi*J + j];
					//if (r[di*J + k]*J < trap) break;
					r[wi*J + k] = 0.0;
				}
				for (i=jc[wi]; i<jc[wi + 1]; i++) {
					di = (int) ir[i];
					xi = sr[i];
					mutot = 0.0;
					totprob = 0.0;
					for (j=0; j < (int) (J*threshold); j++) {
						k = (int) indx_r[wi*J + j];
						theta[di*J + k] -= xi*mu[i*J + k];	
						totprob += mu[i*J + k];
						munew[k] = (phi[wi*J + k] + BETA)/(phitot[k] + WBETA)*(theta[di*J + k] + ALPHA);
						mutot += munew[k];
					}
					for (j=0; j < (int) (J*threshold); j++) {
						k = (int) indx_r[wi*J + j];
						munew[k] /= mutot;
						munew[k] *= totprob;
						r[wi*J + k] += xi*fabs(munew[k] - mu[i*J + k]);
						mu[i*J + k] = munew[k];
						theta[di*J + k] += xi*mu[i*J + k];
					}
				}
				insertionsort(J, r + wi*J, indx_r + wi*J);
			}
		}
	}
}
int main()
{
   int edges;
   int vertices;
   int i=0, j=0, weight = 0, v1, v2, w;
   scanf("%d%d",&vertices,&edges);
   struct dslist v[vertices];
   struct edges e[edges];
   struct edges S[edges];
   int temp = edges; 
   while(edges){
   --edges;
   scanf("%d%d%d",&v1,&v2,&w);
   e[i].start = v1;
   e[i].end = v2;
   e[i].weight = w;
   i++;
   }
   
   first = NULL;
   last = NULL;
   struct dslist *node;
   node = first;
   for(i=0; i<vertices;  i++)
   {     struct ds *nd;
         nd = (struct ds *) malloc (sizeof (struct ds));
         nd->key = i;
         nd->p = NULL;
         nd->rank = 0;

         struct dslist *ndstr;
         ndstr = (struct dslist *) malloc (sizeof (struct dslist));
         ndstr->elem = nd;
         ndstr->next = NULL;
         if(first == NULL)
            {first = ndstr;
            first->next = NULL;
            last = first;}
         else{
            last->next = ndstr;
            last = ndstr;     
         }
         makeset(nd);
      };
   
   insertionsort(e, temp);
   for(i=0;i<temp; i++)
   {
      if((find(retpoint(e[i].start)))->key != (find(retpoint(e[i].end)))->key)
      {  S[j] = e[i];
         j++;
         combine(retpoint(e[i].start), retpoint(e[i].end));
      }
   }
   //printf("\n SORTED:");
   for(i=0; i<j; i++)
   {  weight += S[i].weight;
      //printf("%d %d",S[i].start,S[i].end);
   }
   
   printf("WEIGHT: %d\n",weight);
   print_matrix(S, vertices);

   return 0;
}
void main() {
	int *niz;
	double n;
	float k;
	int *niz1, *niz2;
	double seltime, instime, quicktime, quicktime_new, quick_sorted, quick_sorted_pivot, mergetime;

	srand((unsigned int)time(0));

	/*
	// Ti(n) = 1 + 5*n + n^2
	// Tq(n) = (2*n-1) + 4 * (2^(k+1)-1) +  3 * n * k + n { sa k = log(n) }
	for(n=2; n < 64; n=n*2) {
		k = (log10(n)/log(2.0));

		printf("n: %.f\t",n);
		printf("Insertion: %f\t", (1 + 5*n + pow(n,2))); // Slozenost Insertionsort-a
		printf("Quicksort: %f\n", ((2*n-1) + 4 * (pow(2,(k + 1))-1) +  3 * n * k + n)); // Slozenost Quicksort-a
	}
	*/
	
	/*
	for (c = 2; c < 64; c = c * 2) {
		niz1 = generate(30000);
		niz2 = generate(30000);
		printf("c: %d\t", c);
		printf("Quicksort: %f\t", measure(quicksort, niz1, 30000));
		printf("Quicksort_test: %f\n", measure(quicksort_test, niz2, 30000));
	}
	*/

	seltime = instime = quicktime = quicktime_new = quick_sorted = quick_sorted_pivot = mergetime = 0;
	for (n = 1000; n < 20000; n += 1000) {
		/* 
		niz = generate(n);
		seltime = measure(selectionsort,niz, n);
		free(niz);

		niz = generate(n);
		instime = measure(insertionsort, niz, n);
		free(niz);

		niz = generate(n);
		mergetime = measure(mergesort, niz, n);
		free(niz);
		*/

		
		niz = generate(n);
		insertionsort(niz, n);
		
		niz1 = duplicate(niz, n);
		niz2 = duplicate(niz, n);
		
		/* QUICK SORT ZA SORTIRANI NIZ */
		quick_sorted = measure(quicksort, niz1, n);
		quick_sorted_pivot = measure(quicksort_new, niz2, n);
		free(niz);

		free(niz1);
		free(niz2);
		
		/* QUICK SORT ZA SLUCAJNI NIZ */
		niz = generate(n);
		quicktime = measure(quicksort, niz, n);
		free(niz);

		niz = generate(n);
		quicktime_new = measure(quicksort_new, niz, n);
		free(niz);
		

		printf("%lf %lf %f %f\n", quicktime, quicktime_new, quick_sorted, quick_sorted_pivot);
		
	}
}
Example #26
0
// unrolled insertionsort
void insertionsort1(int N, int M) {
  insertionsort(N, M);
  /*
  if ( M <= N ) return;
  // M <= N + 10 
  register int i, s;
  int minimumPosition;
  void *minimum, *next, *ai;
  minimumPosition = N;
  minimum = A[N];
  for ( i = N+1; i <= M; i++ ) {
    ai = A[i];
    // if ( ai < minimum ) {
    if ( compareXY(ai, minimum) < 0 ) {
      minimum = ai;
      minimumPosition = i;
    }
  }
  if ( N != minimumPosition ) {
    A[minimumPosition] = A[N];
    A[N] = minimum;
  }
  s = N+1;
  // if ( M == s ) return;
  while ( s < M ) {
    s=s+1;
    next=A[s];
    ai = A[s-1];
    // if ( ai <= next ) continue;
    if ( compareXY(ai, next) <= 0 ) continue;
    A[s] = ai;
    ai = A[s-2];
    if ( compareXY(ai, next) <= 0 ) { A[s-1] = next; continue; }
    A[s-1] = ai;
    ai = A[s-3];
    if ( compareXY(ai, next) <= 0 ) { A[s-2] = next; continue; }
    A[s-2] = ai;
    ai = A[s-4];
    if ( compareXY(ai, next) <= 0 ) { A[s-3] = next; continue; }
    A[s-3] = ai;
    ai = A[s-5];
    if ( compareXY(ai, next) <= 0 ) { A[s-4] = next; continue; }
    A[s-4] = ai;
    ai = A[s-6];
    if ( compareXY(ai, next) <= 0 ) { A[s-5] = next; continue; }
    A[s-5] = ai;
    ai = A[s-7];
    if ( compareXY(ai, next) <= 0 ) { A[s-6] = next; continue; }
    A[s-6] = ai;
    ai = A[s-8];
    if ( compareXY(ai, next) <= 0 ) { A[s-7] = next; continue; }
    A[s-7] = ai;
    ai = A[s-9];
    if ( compareXY(ai, next) <= 0 ) { A[s-8] = next; continue; }
    A[s-8] = ai;
    ai = A[s-10];
    if ( compareXY(ai, next) <= 0 ) { A[s-9] = next; continue; }
    A[s-9] = ai;
    ai = A[s-11];
    if ( compareXY(ai, next) <= 0 ) { A[s-10] = next; continue; }
    A[s-10] = ai;
    ai = A[s-12];
    if ( compareXY(ai, next) <= 0 ) { A[s-11] = next; continue; }

    fprintf(stderr, "FourSort/ insertionsort() ");
    fprintf(stderr, "N: %d M %d s: s\n", N, M, s);
    exit(1);
  }
  return;
  */
} // end insertionsort1
Example #27
0
// Quicksort equipped with a defense against quadratic explosion;
// calling heapsort if depthlimit exhausted
void quicksort0c(int N, int M, int depthLimit) {
  // printf("Enter quicksort0c N: %d M: %d %d\n", N, M, depthLimit);
  while ( N < M ) {
    int L = M - N;
    if ( L <= 10 ) {
      insertionsort(N, M);
      return;
    }
    if ( depthLimit <= 0 ) {
      heapc(A, N, M);
      return;
    }
    depthLimit--;
    // 10 < L
    // grab median of 3 or 9 to get a good pivot
    int pn = N;
    int pm = M;
    int p0 = (pn+pm)/2;
    if ( 40 < L ) { // do median of 9
      int d = L/8;
      pn = med(A, pn, pn + d, pn + 2 * d, compareXY);
      p0 = med(A, p0 - d, p0, p0 + d, compareXY);
      pm = med(A, pm - 2 * d, pm - d, pm, compareXY);
      /* Activation of the check for duplicates gives a slow down of 
	 1/4% on uniform input.  If you suspect that duplicates
	 causing quadratic deterioration are not caught higher-up by cut3
	 you may want to experiment with this check::::
      if ( L < 100 ) { // check for duplicates
	int duplicate = -1;
	if ( compareXY(A[pn], A[pm]) == 0 ) { duplicate = pn; } else
	if ( compareXY(A[pn], A[p0]) == 0 ) { duplicate = pn; } else
	if ( compareXY(A[pm], A[p0]) == 0 ) { duplicate = pm; };
	if ( 0 < duplicate ) {
	  void quicksort0();
	  cut3duplicates(N, M, duplicate, quicksort0, depthLimit);
	  return;
	}
      }
      */
    }
    p0 = med(A, pn, p0, pm, compareXY); // p0 is index to 'best' pivot ...
    iswap(N, p0, A); // ... and is put in first position as required by quicksort0c

    register void *p = A[N]; // pivot
    register int i, j;
    i = N;
    j = M;
    register void *ai; void *aj;

    /* Split array A[N,M], N<M in two segments using pivot p; 
       construct a partition with A[N,i), A(i,M] and N <= i <= M, and
       N <= k <= i -> A[k] <= p  and  i < k <= M -> p < A[k];
       Allow the worse cases: N=i or i=M.
       Recurse on A[N,i) and A(i,M) (or in the reverse order).
       This code does NOT do swapping; instead it disposes 
       ai/aj in a hole created by setting aj/ai first.  
    */
    /* Start state:
	  |-------------------------------|
          N=i                           j=M
	  N = i < j = M
          N <= k < i -> A[k] <= p    
          N < j < k <= M -> p < A[k]
	  A[N] = p
          N < i -> p < A[i]
    */
    while ( i < j ) {
      /*
	  |-------o---------------[--------|
          N       i               j        M
	  N <= i < j <= M
          N <= k < i -> A[k] <= p    
          N < j < k <= M -> p < A[k]
	  A[N] <= p
          N < i -> p < A[i]
          p + A[N,i) + A(i,M] is a permutation of the input array
      */
      aj = A[j];
      while ( compareXY(p, aj) < 0 ) { 
        /*
	  |-------o---------------[--------|
          N       i               j        M
	  N = i < j <= M or N < i <= j <= M
          N <= k < i -> A[k] <= p    
          N < j <= k <= M -> p < A[k]
	  A[N] <= p
	  N < i -> p < A[i}
	  p + A[N,i) + A(i,M] is a permutation of the input array
          p < aj = A[j]
	*/
	j--; 
	aj = A[j]; 
      }
      /*
	  |-------o---------------[--------|
          N       i               j        M
	  N = i = j < M or N < i & = i-1 <= j <= M
          N <= k < i -> A[k] <= p    
          j < k <= M -> p < A[k]
	  A[N] <= p
	  N < i -> p < A[i}
	  p + A[N,i) + A(i,M] is a permutation of the input array
          aj = A[j] <= p
	*/
      if ( j <= i ) {
	/*
	  |-------o-----------------------|
          N       i                       M
	  N = i = j < M or N < i & = i-1 = j < M
          N <= k < i -> A[k] <= p    
          i < k <= M -> p < A[k]
	  A[N] <= p
	  p + A[N,i) + A(i,M] is a permutation of the input array
      */
	break;
      }
      // i < j 
      A[i] = aj; // fill hole !
      /*
	  |-------]---------------o--------|
          N       i               j        M
	  N <= i < j <= M
          N <= k <= i -> A[k] <= p    
          j < k <= M -> p < A[k]
	  A[N] <= p
	  p + A[N,j) + A(j,M] is a permutation of the input array
	  aj = A[j] <= p
      */
      i++; ai = A[i];
      while ( i < j && compareXY(ai, p) <= 0 ) {
      /*
	  |-------]---------------o--------|
          N       i               j        M
	  N < i < j <= M
          N <= k <= i -> A[k] <= p    
          j < k <= M -> p < A[k]
	  A[N] <= p
	  p + A[N,j) + A(j,M] is a permutation of the input array
	  aj = A[j] <= p
      */
	i++; ai = A[i]; 
      }
      if ( j <= i ) 
      /*
	  |----------------------o--------|
          N                     i=j       M
	  N < i = j <= M
          N <= k < i -> A[k] <= p    
          j < k <= M -> p < A[k]
	  A[N] <= p
	  p + A[N,j) + A(j,M] is a permutation of the input array
      */
	break;
      // i < j  & p < ai = A[i] 
      A[j] = ai;
      j--;
      /*
	  |--------o--------------[--------|
          N        i              j        M
	  N < i <= j <= M
          N <= k < i -> A[k] <= p    
          j < k <= M -> p < A[k]
	  A[N] <= p
          N < i -> p < ai = A[i]
	  p + A[N,i) + A(i,M] is a permutation of the input array
      */
    }
    A[i] = p;
    /*
	  |--------]----------------------|
          N        i                      M
	  N <= i <= M
          N <= k <= i -> A[k] <= p    
          i < k <= M -> p < A[k]
	  A[N] <= p
	  A[N,i] + A(i,M] is a permutation of the input array
    */
    // Recurse on the smallest one and iterate on the other one
    int ia = i-1; int ib = i+1; 
    if ( i-N < M-i ) { 
      if ( N < ia ) quicksort0c(N, ia, depthLimit);  
      N = ib; 
    } else { 
      if ( ib < M ) quicksort0c(ib, M, depthLimit);  
      M = ia; 
    }
  }
} // end of quicksort0c
Example #28
0
void ParallelSort::modified_quicksort(vector<T> &array, int head, int tail)
{
        if (head >= tail)
            return;

        int len = tail - head + 1;
        // use insertion sort if datasize < INSER...
        if (len <= INSERTION_QUICK_SWITCH) 
        {
        	//insertionsort(array, head, tail);
  	        insertionsort(array, head, tail);
  //           for (int i=head; i <= tail; i++) 
		// 	{
		// //#pragma omp parallel for private(j)
		// 		for (int j = i; j > head && array[j - 1] > array[j]; j--) 
		// 		{
		// 			swap(array, j, j - 1);
		// 		}
		// 	}
        }

        // Find the pivot
        int mid = head + (len >> 1);
        if (len > INSERTION_QUICK_SWITCH) {
            int left = head;
            int right = head + len - 1;
            if (len > 40) {
                int s = len / 8;
                left = median(array, left, left + s, left + 2 * s);
                mid = median(array, mid - s, mid, mid + s);
                right = median(array, right - 2 * s, right - s, right);
            }
            mid = median(array, left, mid, right);
        }

        T the = array[mid];

        //a,b scan from left and c,d scan from right
        int l1 = head, l2 = l1, r1 = head + len - 1, r2 = r1;
        while (true) {
            //try to find element bigger than pivot
            while (l2 <= r1 && array[l2] <= the) {
                //swap the element same as pivot to the left
                if (array[l2] == the)
                    swap(array, l1++, l2);
                l2++;
            }
            //try to find element smaller than pivot
            while (r1 >= l2 && array[r1] >= the) {
                //swap the element same as pivot to the left
                if (array[r1] == the)
                    swap(array, r1, r2--);
                r1--;
            }
            if (l2 > r1)
                break;
            //swapping
            swap(array, l2++, r1--);
        }

        //swap the same elements to the middle
        int small, sum = head + len;
        small = min(l1 - head, l2 - l1);
        groupswap(array, head, l2 - small, small);
        small = min(r2 - r1, sum - r2 - 1);
        groupswap(array, l2, sum - small, small);

        //recursion
        if ((small = l2 - l1) > 1)
            modified_quicksort(array, head, small + head - 1);
        if ((small = r2 - r1) > 1)
            modified_quicksort(array, sum - small, sum - 1);

    //}
	// int pivotele;
	// int i=head-1, j=tail;
	// if(tail-head<INSERTION_QUICK_SWITCH)
	// {
	// 	insertionsort(array, head, tail);
	// 	return;
	// }

	// if(head<tail)
	// {
	// 	pivotele=pivot(array, head, tail);
	// 	modified_quicksort(array, head, pivotele-1);
	// 	modified_quicksort(array,pivotele+1,tail);
	// }
}