示例#1
0
static int archive_compare_files(const void *a, const void *b, void *thunk) {
#else
// OSX, *BSD
static int archive_compare_files(void *thunk, const void *a, const void *b) {
#endif
    return english_compare_natural((((struct archive *)thunk)->names[*((int*)a)]),
                                   (((struct archive *)thunk)->names[*((int*)b)]));
}

static void archive_make_map(struct archive *ar) {
    for (int i = 0; i < ar->files; i++)
        ar->map[i] = i;

#ifdef __gnu_linux__
    qsort_r(&(ar->map), ar->files, sizeof(int), archive_compare_files, (void*)ar);
#else
    // OSX, *BSD
    qsort_r(&(ar->map), ar->files, sizeof(int), (void*)ar, archive_compare_files);
#endif
}

//////////////////////////////////////////////////////////////////////

static void archive_free(struct archive *ar) {
    free(ar);
}
void qsort_r( int* ar, int start, int end )
{
	int l = start;
	int r = end;
	int p = ar[start];

	if( start >= end )
		return;

	while( l < r )
	{
		if( ar[l] <= p )
			l++;
		else if( ar[r] >= p )
			r--;
		else
			swap( ar+l, ar+r );
	}

	if( ar[l] < p )
	{
		swap( ar+start, ar+l );
		l--;
	}
	else
	{
		l--;
		swap( ar+start, ar+l );
	}

	qsort_r( ar, start, l );
	qsort_r( ar, r, end );

	return;
}
示例#3
0
文件: nsga2.c 项目: Tefx/MoWSC
void crowd_cut(list** l, size_t nn, size_t n, size_t m, double* xs, double* ys) {
    double* dis = (double*) malloc(sizeof(double) * nn);
    size_t* a = (size_t*) malloc(sizeof(size_t) * n);
    list* tmp;
    int k = 0;

    for (size_t i=0; i<nn; i++) dis[i] = 0;

    while (*l) {
        a[k++] = (*l)->data;
        tmp = *l;
        *l = (*l)->next;
        free(tmp);
    }


    qsort_r(a, n, sizeof(size_t), cmp_l, xs);
    dis[a[0]] = dis[a[n-1]] = INF;
    if (xs[a[n-1]] != xs[a[0]])
        for (size_t i=1; i<n-1; i++)
            dis[a[i]] += (xs[a[i+1]] - xs[a[i-1]]) / (xs[a[n-1]] - xs[a[0]]);

    qsort_r(a, n, sizeof(size_t), cmp_l, ys);
    dis[a[0]] = dis[a[n-1]] = INF;
    if (ys[a[n-1]] != ys[a[0]])
        for (size_t i=1; i<n-1; i++)
            dis[a[i]] += (ys[a[i+1]] - ys[a[i-1]]) / (ys[a[n-1]] - ys[a[0]]);

    qsort_r(a, n, sizeof(size_t), cmp_l, dis);
    for (size_t i=1; i<=m; i++)
        add_item(l, a[n-i]);

    free(a);
    free(dis);
}
示例#4
0
void
tvh_qsort_r(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *, void *), void *arg)
{
#if defined(PLATFORM_FREEBSD) || defined(PLATFORM_DARWIN)
    struct tvh_qsort_data swap_arg = {arg, compar};
    qsort_r(base, nmemb, size, &swap_arg, tvh_qsort_swap);
#else
    qsort_r(base, nmemb, size, compar, arg);
#endif
}
示例#5
0
void QuickSort( void *base, size_t num, size_t width, void *context,
							int ( *compare )(void *, const void *, const void *) ) {
#if OG_WIN32
	qsort_s( base, num, width, compare, context );
#elif OG_MACOS_X
	qsort_r( base, num, width, context, compare );
#elif OG_LINUX
	CompareWrapper data(context, compare);
	qsort_r( base, num, width, CompareWrapper::Compare, &data );
#endif
}
示例#6
0
static int compare_for_sort_index (const void *v1, const void *v2)
{
#elif defined(HAVE_QSORT_R)
static int compare_for_sort_index (void *thunk, const void *v1, const void *v2)
{
  const int *tab_to_sort = thunk;
#else 
#error "please provide some kind of thread-local storage"
#endif
  
  int dt = tab_to_sort[*(int *)v1] - tab_to_sort[*(int *)v2];
  if (dt) 
    return dt;
  return *(int *)v1 - *(int *)v2;
}


void ivec_sort_index (const int *tab, int n, int *perm) 
{
  int i;

  for (i = 0 ; i < n ; i++) 
    perm[i] = i;

#ifdef HAVE_TLS
  tab_to_sort = tab;
  qsort (perm, n, sizeof(int), compare_for_sort_index);
#elif defined(HAVE_QSORT_R)
  qsort_r (perm, n, sizeof(int), (void*)tab, compare_for_sort_index);
#endif
}
示例#7
0
void polygon(POINT *points[], size_t n)
{
    // According to Wikipedia, a polygon of one point is a point and a polygon
    // of two is a straight line and they are both valid.
    assert (n >= 1);

    // Extracts the leftmost point and swaps it with the first point of the
    // array.
    for (size_t i = 1; i < n; i++) {
        if (points[i]->x < points[0]->x) {
            POINT *tmp = points[i];
            points[i] = points[0];
            points[0] = tmp;
        }
    }

    // Uses the leftmost point as the first point of the polygon.
    // Sort the remainder of the vector by comparing the relative slope of each
    // point to this first point.
    qsort_r(points + 1, n - 1, sizeof (POINT *), point_cmp, (void *) points[0]);

    // By selecting the leftmost point, I'm able to compare points by their
    // slopes instead of their angles (because I don't care in which side of the
    // first point they sit).
    // This is way faster because I avoid expensive trigonometric computations.
    // Moreover, as the computation and comparison of two slopes is fast, I
    // don't cache them.
}
示例#8
0
文件: fts.c 项目: outbackdingo/uBSD
static FTSENT *
fts_sort(FTS *sp, FTSENT *head, size_t nitems)
{
	FTSENT **ap, *p;

	/*
	 * Construct an array of pointers to the structures and call qsort(3).
	 * Reassemble the array in the order returned by qsort.  If unable to
	 * sort for memory reasons, return the directory entries in their
	 * current order.  Allocate enough space for the current needs plus
	 * 40 so don't realloc one entry at a time.
	 */
	if (nitems > sp->fts_nitems) {
		sp->fts_nitems = nitems + 40;
		if ((sp->fts_array = reallocf(sp->fts_array,
		    sp->fts_nitems * sizeof(FTSENT *))) == NULL) {
			sp->fts_nitems = 0;
			return (head);
		}
	}
	for (ap = sp->fts_array, p = head; p; p = p->fts_link)
		*ap++ = p;
	if (ISSET(FTS_COMPAR_B))
		qsort_r(sp->fts_array, nitems, sizeof(FTSENT *),
			sp->fts_compar_b, fts_compar_b);
	else
		qsort(sp->fts_array, nitems, sizeof(FTSENT *), fts_compar);
	for (head = *(ap = sp->fts_array); --nitems; ++ap)
		ap[0]->fts_link = ap[1];
	ap[0]->fts_link = NULL;
	return (head);
}
示例#9
0
/* Compute (and allocate) migration price matrix for optimization */
static void
price_routes(PRICEMAT *pm, const RBFNODE *from_rbf, const RBFNODE *to_rbf)
{
	FVECT	*vto = (FVECT *)malloc(sizeof(FVECT) * to_rbf->nrbf);
	int	i, j;

	pm->nrows = from_rbf->nrbf;
	pm->ncols = to_rbf->nrbf;
	pm->price = (float *)malloc(sizeof(float) * pm->nrows*pm->ncols);
	pm->sord = (short *)malloc(sizeof(short) * pm->nrows*pm->ncols);
	
	if ((pm->price == NULL) | (pm->sord == NULL) | (vto == NULL)) {
		fprintf(stderr, "%s: Out of memory in migration_costs()\n",
				progname);
		exit(1);
	}
	for (j = to_rbf->nrbf; j--; )		/* save repetitive ops. */
		ovec_from_pos(vto[j], to_rbf->rbfa[j].gx, to_rbf->rbfa[j].gy);

	for (i = from_rbf->nrbf; i--; ) {
	    const double	from_ang = R2ANG(from_rbf->rbfa[i].crad);
	    FVECT		vfrom;
	    ovec_from_pos(vfrom, from_rbf->rbfa[i].gx, from_rbf->rbfa[i].gy);
	    for (j = to_rbf->nrbf; j--; ) {
		double		dprod = DOT(vfrom, vto[j]);
		pricerow(pm,i)[j] = ((dprod >= 1.) ? .0 : acos(dprod)) +
				fabs(R2ANG(to_rbf->rbfa[j].crad) - from_ang);
		psortrow(pm,i)[j] = j;
	    }
	    qsort_r(psortrow(pm,i), pm->ncols, sizeof(short), pm, &msrt_cmp);
	}
	free(vto);
}
示例#10
0
int main() {
    int array;
    int baton;
    qsort_r(&array, 1, sizeof(int), &baton, cmp);
    //printf("#define NEED_QSORT_R 0\n");
    return 0;
}
示例#11
0
文件: vector.c 项目: armistace/wget2
void wget_vector_sort(wget_vector_t *v)
{
	if (v && v->cmp) {
		qsort_r(v->entry, v->cur, sizeof(void *), _compare, v);
		v->sorted = 1;
	}
}
示例#12
0
void
qsort_b(void *base, size_t nel, size_t width,
	DECLARE_BLOCK(int, compar, const void *, const void *))
{
	qsort_r(base, nel, width, compar,
		(int (*)(void *, const void *, const void *))
		GET_BLOCK_FUNCTION(compar));
}
示例#13
0
int main() {
    int array[] = { 4, 17, 88, 34, 12, 12, 17 };
    int N = sizeof(array)/sizeof(int);
    int mythunk = 42;
    qsort_r(array, N, sizeof(int), &mythunk, sortfunc);
    //printf("#define NEED_SWAP_QSORT_R 0\n");
    return 0;
}
示例#14
0
文件: sset.c 项目: postfix/quake2vr
void Q_SSetReverseSort(sset_t *ss, qboolean caseSensitive) {
    int (*func)(void *, const void *, const void *) = caseSensitive ? revtokcmp : revtokcasecmp;
#ifdef WIN32
    qsort_s(&ss->tokens[0], ss->currentSize, sizeof(int32_t), func, (void *)&ss->table);
#else
    qsort_r(&ss->tokens[0], ss->currentSize, sizeof(int32_t), (void *)&ss->table, func);
#endif
}
示例#15
0
static void printObj(CFPropertyListRef obj, struct printContext* c) {
	CFTypeID typeID = CFGetTypeID(obj);
	if (typeID == _CFKeyedArchiverUIDGetTypeID()) {
		unsigned uid = _CFKeyedArchiverUIDGetValue(obj);
		CFPropertyListRef refObj = CFArrayGetValueAtIndex(c->objs, uid);
		if (CFEqual(refObj, CFSTR("$null")))
			printf("nil");
		else if (c->refCount[uid] > 1 && isComplexObj(refObj))
			printf("{CF$UID = %u;}", uid);
		else
			printObj(refObj, c);
	} else if (typeID == CFArrayGetTypeID()) {
		printf("(\n");
		++ c->tabs;
		CFArrayApplyFunction(obj, CFRangeMake(0, CFArrayGetCount(obj)), (CFArrayApplierFunction)&printObjAsArrayEntry, c);
		-- c->tabs;
		for (unsigned i = 0; i < c->tabs; ++ i)
			printf("\t");
		printf(")");
	} else if (typeID == CFDictionaryGetTypeID()) {
		CFStringRef className = CFDictionaryGetValue(obj, CFSTR("$classname"));
		if (className != NULL)
			printObjAsClassName(className);
		else {
			printf("{\n");
			++ c->tabs;
			CFIndex dictCount = CFDictionaryGetCount(obj);
			
			struct dictionarySorterContext sc;
			sc.keys = malloc(sizeof(CFStringRef)*dictCount);
			sc.values = malloc(sizeof(CFPropertyListRef)*dictCount);
			unsigned* mapping = malloc(sizeof(unsigned)*dictCount);
			for (unsigned i = 0; i < dictCount; ++ i)
				mapping[i] = i;
			CFDictionaryGetKeysAndValues(obj, (const void**)sc.keys, sc.values);
			qsort_r(mapping, dictCount, sizeof(unsigned), &sc, (int(*)(void*,const void*,const void*))&dictionaryComparer);
			for (unsigned i = 0; i < dictCount; ++ i)
				printObjAsDictionaryEntry(sc.keys[mapping[i]], sc.values[mapping[i]], c);
			free(mapping);
			free(sc.keys);
			free(sc.values);
			-- c->tabs;
			for (unsigned i = 0; i < c->tabs; ++ i)
				printf("\t");
			printf("}");
		}
	} else if (typeID == CFDataGetTypeID())
		printObjAsData(obj);
	else if (typeID == CFNumberGetTypeID())
		printObjAsNumber(obj);
	else if (typeID == CFStringGetTypeID())
		printObjAsString(obj);
	else if (typeID == CFBooleanGetTypeID())
		printf(CFBooleanGetValue(obj) ? "true" : "false");
	else if (typeID == CFDateGetTypeID()) 
		printf("/*date*/ %0.09g", CFDateGetAbsoluteTime(obj));

}
示例#16
0
void color_table_sort(color_table table, axis component)
{
	
	/* Condition d'erreur qui permetent de quitter la focntion si necessaire*/
	assert(table != NULL);
	
	qsort_r(table->colors, color_table_get_nb_color(table), sizeof(color), compare, &component);
	
}
示例#17
0
文件: kenken.c 项目: dlowe/kenken
puzzle_size compute_puzzle_size(IplImage *puzzle, IplImage **annotated) {
    IplImage *threshold_image = _grid(puzzle);

    *annotated = cvCloneImage(puzzle);
    cvCvtColor(threshold_image, *annotated, CV_GRAY2RGB);

    // the logic here is to "rank" the possible sizes, by computing the average pixel intensity
    // in the vicinity of where the lines should be.
    unsigned short guess_id = 0;
    puzzle_size guesses[PUZZLE_SIZE_MAX - PUZZLE_SIZE_MIN + 1];
    unsigned long means[PUZZLE_SIZE_MAX + 1];

    const int fuzz = threshold_image->width / 50;
    for (puzzle_size guess_size = PUZZLE_SIZE_MIN; guess_size <= PUZZLE_SIZE_MAX; ++guess_size) {
        guesses[guess_id++] = guess_size;
        means[guess_size] = 0;

        for (unsigned short i = 1; i < guess_size; ++i) {
            int center = i * (threshold_image->width / guess_size);
            for (int x = 0; x < threshold_image->width; ++x) {
                for (int y = center - fuzz; y < center + fuzz; ++y) {
                    CvScalar s = cvGet2D(threshold_image, y, x);
                    means[guess_size] += s.val[0];
                }
            }
            for (int x = center - fuzz; x < center + fuzz; ++x) {
                for (int y = 0; y < threshold_image->height; ++y) {
                    CvScalar s = cvGet2D(threshold_image, y, x);
                    means[guess_size] += s.val[0];
                }
            }
        }
        means[guess_size] /= (guess_size - 1);
    }

    qsort_r(guesses, sizeof(guesses) / sizeof(puzzle_size), sizeof(puzzle_size), (void *)means, _compare_means);

    puzzle_size size = guesses[0];

    // evenly divisible sizes are easily confused. Err on the side of the larger size puzzle.
    puzzle_size confusable[][2] = { { 4, 8 }, { 3, 9 }, { 3, 6 } };
    for (int i = 0; i < (sizeof(confusable) / sizeof(puzzle_size) / 2); ++i) {
        if ((guesses[0] == confusable[i][0]) && (guesses[1] == confusable[i][1]) && (means[guesses[0]] - means[guesses[1]] < means[guesses[1]] - means[guesses[2]])) {
            size = confusable[i][1];
            break;
        }
    }

    for (unsigned short i = 1; i < size; ++i) {
        int center = i * (threshold_image->width / size);
        cvRectangle(*annotated, cvPoint(0, center - fuzz), cvPoint(threshold_image->width, center + fuzz), CV_RGB(255, 0, 0), 2, 8, 0);
        cvRectangle(*annotated, cvPoint(center - fuzz, 0), cvPoint(center + fuzz, threshold_image->height), CV_RGB(255, 0, 0), 2, 8, 0);
    }
    cvReleaseImage(&threshold_image);

    return size;
}
示例#18
0
/**
 * Sort endpoints in place in descending order of preference.
 * @param endpoints array of endpoint pointers.
 */
static void
endpoints_preference_sort(const as_endpoint* endpoints[], size_t n_endpoints)
{
	// Random tie breaker to load balance between two equivalent endpoints.
	int tie_breaker = rand();

	qsort_r(endpoints, n_endpoints, sizeof(as_endpoint*),
		endpoint_preference_compare, &tie_breaker);
}
示例#19
0
文件: ensobs.c 项目: juicydut/enkf-c
/** Sorts all observations by j,i so that they can be processed in a single
 * cycle over horizontal grid cells.
 */
static void das_sortobs_byij(dasystem* das)
{
    observations* obs = das->obs;
    int o, e;

    if (das->sort_mode == OBS_SORTMODE_IJ)
        return;
    if (obs->nobs == 0)
        return;

    enkf_printf("    sorting obs by ij:\n");
    qsort_r(obs->data, obs->nobs, sizeof(observation), cmp_obs_byij, das);

    if (das->s_f != NULL) {
        double* s = calloc(obs->nobs, sizeof(double));

        for (o = 0; o < obs->nobs; ++o)
            s[o] = das->s_f[obs->data[o].id];
        memcpy(das->s_f, s, obs->nobs * sizeof(double));

        for (o = 0; o < obs->nobs; ++o)
            s[o] = das->std_f[obs->data[o].id];
        memcpy(das->std_f, s, obs->nobs * sizeof(double));

        free(s);
    }

    if (das->s_a != NULL) {
        double* s = calloc(obs->nobs, sizeof(double));

        for (o = 0; o < obs->nobs; ++o)
            s[o] = das->s_a[obs->data[o].id];
        memcpy(das->s_a, s, obs->nobs * sizeof(double));

        for (o = 0; o < obs->nobs; ++o)
            s[o] = das->std_a[obs->data[o].id];
        memcpy(das->std_a, s, obs->nobs * sizeof(double));

        free(s);
    }

    {
        ENSOBSTYPE* S = calloc(obs->nobs, sizeof(ENSOBSTYPE));

        for (e = 0; e < das->nmem; ++e) {
            ENSOBSTYPE* Se = das->S[e];

            for (o = 0; o < obs->nobs; ++o)
                S[o] = Se[obs->data[o].id];
            memcpy(Se, S, obs->nobs * sizeof(ENSOBSTYPE));
        }
        free(S);
    }

    das->sort_mode = OBS_SORTMODE_IJ;
}
示例#20
0
文件: util.c 项目: psclib/pscgen
void d_argsort(double *vec, int *idxs, int N)
{
    int i;
    for(i = 0; i < N; i++) {
        idxs[i] = i;
    }

    /* perform qsort */
    qsort_r(idxs, N, sizeof(int), d_argsort_compare, (void *)vec);
}
void
qsort_r (void *base, size_t nmemb, size_t size,
         int (*cmp) (void const *, void const *, void *),
         void *arg)
{
# undef qsort_r
  struct thunk thunk;
  thunk.cmp = cmp;
  thunk.arg = arg;
  qsort_r (base, nmemb, size, &thunk, thunk_cmp);
}
int main (int argc, char *argv[])
{
	int i;

	//to hold our pointer to many pointers
	int **array;

	//to pass to our qsort_r
	void *dummy;

	if(argc<3)
	{
		fprintf(stderr, "Error: Please enter a space separated list of ints to be sorted " 
			"from the command line. Example: %s 6 9 12\n",argv[0] );
		exit(EXIT_FAILURE);
	}

	//create an array of pointers with amount of args they passed in 
	array = malloc(sizeof(int*)*(argc-1));

	fprintf(stderr, "Before qsort_r\n");
	for(i=0; i<argc-1;i++)
	{
		//array[i] ...if that helps
		*(array+i) = malloc(sizeof(int));


		//store the value of argv in *array[i] 
		*(*(array+i)) = atoi(argv[i+1]);
		
		fprintf(stderr, "*(array+i) &:%p the value in *(*(array+i)):%d\n",*(array+i), *(*(array+i)) );
		//fprintf(stderr, "[%d] %d\n", i, *(*(array+i)));	
	}

	//args: the array to be sorted, the amount of elements in the array, the sizeof those elements,
	//	and a dummy variable
	qsort_r(array,argc-1,sizeof(int*),compf,dummy);
	

	fprintf(stderr, "After qsort_r\n" );
	for(i=0; i<argc-1;i++)
	{
		fprintf(stderr, "*(array+i) &:%p the value in *(*(array+i)):%d\n",*(array+i), *(*(array+i)) );
		//fprintf(stderr, "[%d] %d\n", i, *(*(array+i)));	

		free(*(array+i));

	}

	free(array);

}
示例#23
0
文件: list.c 项目: slyrz/klingklang
int
kk_list_sort (kk_list_t *list, kk_list_cmp_f cmp)
{
  if (list->len <= 1)
    return 0;

#ifdef HAVE_QSORT_R
#  ifdef HAVE_QSORT_R_GNU
  qsort_r (list->items, list->len, sizeof (void *), list_compare, cmp);
#  else
  qsort_r (list->items, list->len, sizeof (void *), cmp, list_compare);
#  endif
#else
  pthread_mutex_lock (&mutex);
  arg = cmp;
  qsort (list->items, list->len, sizeof (void *), list_compare);
  arg = NULL;
  pthread_mutex_unlock (&mutex);
#endif

  return 0;
}
示例#24
0
/* ----------------------------------------------------------------------------
k_nearest:
    Tras copiar los datos de entrenamiento al arreglo nearest, lo
    ordena de menor a mayor según la distancia euclidia al punto dado.

    Quedando como primeros elementos del arreglo los datos más
    cercanos al punto dado.
---------------------------------------------------------------------------- */
void k_nearest(double* x) {

  int i;

  /* Copio data a nearest */
  for(i = 0; i < PTOT; i++)
    memcpy(nearest[i], data[i],sizeof(double)*(N_IN+1));

  /* Ordeno nearest segun el valor x dado*/
  qsort_r(nearest, PTOT, sizeof(double*), &cmp, (void*)x);

  return;
}
示例#25
0
文件: hwdb.c 项目: davide125/systemd
static int trie_node_add_value(struct trie *trie, struct trie_node *node,
                               const char *key, const char *value,
                               const char *filename, uint16_t file_priority, uint32_t line_number) {
        ssize_t k, v, fn;
        struct trie_value_entry *val;

        k = strbuf_add_string(trie->strings, key, strlen(key));
        if (k < 0)
                return k;
        v = strbuf_add_string(trie->strings, value, strlen(value));
        if (v < 0)
                return v;
        fn = strbuf_add_string(trie->strings, filename, strlen(filename));
        if (fn < 0)
                return fn;

        if (node->values_count) {
                struct trie_value_entry search = {
                        .key_off = k,
                        .value_off = v,
                };

                val = xbsearch_r(&search, node->values, node->values_count, sizeof(struct trie_value_entry), trie_values_cmp, trie);
                if (val) {
                        /* At this point we have 2 identical properties on the same match-string.
                         * Since we process files in order, we just replace the previous value.
                         */
                        val->value_off = v;
                        val->filename_off = fn;
                        val->file_priority = file_priority;
                        val->line_number = line_number;
                        return 0;
                }
        }

        /* extend array, add new entry, sort for bisection */
        val = reallocarray(node->values, node->values_count + 1, sizeof(struct trie_value_entry));
        if (!val)
                return -ENOMEM;
        trie->values_count++;
        node->values = val;
        node->values[node->values_count].key_off = k;
        node->values[node->values_count].value_off = v;
        node->values[node->values_count].filename_off = fn;
        node->values[node->values_count].file_priority = file_priority;
        node->values[node->values_count].line_number = line_number;
        node->values_count++;
        qsort_r(node->values, node->values_count, sizeof(struct trie_value_entry), trie_values_cmp, trie);
        return 0;
}
示例#26
0
int main( int argc, char** argv )
{
	srand( time( NULL ) );
	int i = 0;
	int asz = rand() % SZ;
	int bsz = rand() % SZ;
	int rsz = asz + bsz;
	int* ar = (int*)calloc( 1, sizeof(int) * asz );
	int* br = (int*)calloc( 1, sizeof(int) * bsz );
	int* result = (int*)calloc( 1, sizeof(int) * rsz );

	for( i = 0; i < asz; i ++ )
		ar[i] = rand() % MAX;
	for( i = 0; i < bsz; i ++ )
		br[i] = rand() % MAX;

	qsort_r( ar, 0, asz - 1 );
	qsort_r( br, 0, bsz - 1 );
	print_array( ar, asz );
	print_array( br, bsz );

	printf( "union: " );
	ar_union( ar, br, asz, bsz, result, rsz );
	print_array( result, rsz );

	for( i = 0; i < rsz; i ++ )
		result[i] = 0;

	printf( "intersection: " );
	ar_intersect( ar, br, asz, bsz, result, rsz );
	print_array( result, rsz );

	if( result ) free( result );
	if( br ) free( br );
	if( ar ) free( ar );
	return 0;
}
示例#27
0
wi_array_t * wi_dictionary_keys_sorted_by_value(wi_dictionary_t *dictionary, wi_compare_func_t *compare) {
    wi_mutable_array_t          *array, *buckets;
    _wi_dictionary_bucket_t     *bucket;
    wi_array_callbacks_t        callbacks;
    void                        **data;
    wi_uinteger_t               i;

    if(dictionary->key_count == 0)
        return wi_autorelease(wi_array_init(wi_array_alloc()));

    callbacks.retain            = NULL;
    callbacks.release           = NULL;
    callbacks.is_equal          = NULL;
    callbacks.description       = NULL;
    buckets                     = wi_array_init_with_capacity_and_callbacks(wi_mutable_array_alloc(), dictionary->key_count, callbacks);

    for(i = 0; i < dictionary->buckets_count; i++) {
        for(bucket = dictionary->buckets[i]; bucket; bucket = bucket->next)
            wi_mutable_array_add_data(buckets, bucket);
    }

    data = wi_malloc(sizeof(void *) * dictionary->key_count);
    wi_array_get_data(buckets, data);

#ifdef _WI_DICTIONARY_USE_QSORT_R
    qsort_r(data, dictionary->key_count, sizeof(void *), compare, _wi_dictionary_compare_buckets);
#else
    wi_lock_lock(_wi_dictionary_sort_lock);
    _wi_dictionary_sort_function = compare;
    qsort(data, dictionary->key_count, sizeof(void *), _wi_dictionary_compare_buckets);
    wi_lock_unlock(_wi_dictionary_sort_lock);
#endif

    callbacks.retain            = dictionary->key_callbacks.retain;
    callbacks.release           = dictionary->key_callbacks.release;
    callbacks.is_equal          = dictionary->key_callbacks.is_equal;
    callbacks.description       = dictionary->key_callbacks.description;
    array                       = wi_array_init_with_capacity_and_callbacks(wi_mutable_array_alloc(), dictionary->key_count, callbacks);

    for(i = 0; i < dictionary->key_count; i++)
        wi_mutable_array_add_data(array, ((_wi_dictionary_bucket_t *) data[i])->key);

    wi_free(data);
    wi_release(buckets);

    wi_runtime_make_immutable(array);

    return wi_autorelease(array);
}
示例#28
0
文件: bwt.c 项目: rcerljenko/bwt
DLL_EXPIMP bwt_size_t CALL_CONV bwt(void* const void_data, const bwt_size_t n)
{
	if(!void_data || n < 2) return 0;

	unsigned char* __restrict data = void_data;
	bwt_size_t i, index = n;
	struct bwt_info_t data_info;
	data_info.rotations = malloc(n * 2 - 1);
	bwt_size_t* __restrict positions = malloc(sizeof(bwt_size_t) * n);

	memcpy(data_info.rotations, data, n);
	memcpy(data_info.rotations + n, data, n - 1);
	data_info.len = n;

	positions += n;
	while((*(--positions) = --index));

#ifdef __linux__
	qsort_r(positions, n, sizeof(bwt_size_t), bwt_cmp, &data_info);
#elif defined(__APPLE__)
	qsort_r(positions, n, sizeof(bwt_size_t), &data_info, bwt_cmp);
#elif defined(_WIN32)
	qsort_s(positions, n, sizeof(bwt_size_t), bwt_cmp, &data_info);
#endif

	for(i = 0; i < n; i++)
	{
		*data++ = data_info.rotations[(*positions + n - 1) % n];
		if(!*positions++) index = i;
	}

	free(positions - n);
	free(data_info.rotations);

	return index;
}
示例#29
0
文件: xstdlib.c 项目: hossbeast/fab
API xapi xqsort_r(void * base, size_t nmemb, size_t size, xapi (*xcompar)(const void *, const void *, void *, int * r), void * arg)
{
  enter;

  struct xqsort_context ctx = { 0 };
  ctx.xcompar = xcompar;
  ctx.arg = arg;

  qsort_r(base, nmemb, size, xqsort_compar, &ctx);

  if(ctx.hasfailed)
    fail(0);

  finally : coda;
}
示例#30
0
int _hx_optimizer_federated_plan_merge( hx_execution_context* ctx, hx_optimizer_plan* plan, void* thunk ) {
	if (plan->type == HX_OPTIMIZER_PLAN_JOIN) {
		hx_optimizer_plan* lhs	= plan->data.join.lhs_plan;
		hx_optimizer_plan* rhs	= plan->data.join.rhs_plan;
		if (lhs->location == rhs->location) {
			plan->location	= lhs->location;
			lhs->location	= 0;
			rhs->location	= 0;
		}
	} else if (plan->type == HX_OPTIMIZER_PLAN_UNION) {
		// now that SERVICE joins have been merged, we should re-order unions to prefer fewer SERVICE calls
		hx_container_t* plans	= plan->data._union.plans;
		qsort_r( plans->items, hx_container_size(plans), sizeof(void*), ctx, hx_optimizer_plan_cmp_service_calls );
	}
	return 0;
}