IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C Discussion :

Reecriture fonction qsort


Sujet :

C

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2006
    Messages
    52
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2006
    Messages : 52
    Par défaut Reecriture fonction qsort
    Bonjour,

    J'essaie de réecrire une fonction de tri (ici, c'est le tri selection) avec la meme entete que celle du qsort.

    Seulement voilà, je me retrouve confronté a des warning, et pas moyen de les enlevés

    Voici le code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    #include <stdio.h>
    #include <stdlib.h>
    #include <stddef.h>
    #include <string.h>
     
    void tri(void *tableau, size_t nb_elements, size_t taille_elements, int(*comp)(const void *, const void *))
    {
         int max, i;
         void *x = (void *)malloc(taille_elements);
     
         while(nb_elements>1)
         {
              max=0;
     
              for(i=1;i<nb_elements;i++)
                   if(comp(tableau+(taille_elements*i),tableau+(taille_elements*max))>0) max=i;
     
              memcpy(x, tableau+(taille_elements*max), taille_elements);
              memcpy(tableau+(taille_elements*max), tableau+(taille_elements*(nb_elements-1)), taille_elements);
              memcpy(tableau+(taille_elements*(nb_elements-1)), x, taille_elements);
     
             nb_elements--;
         }
     
         free(x);
    }
    Voici les warnings générés :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    Selection.c:16: attention : pointer of type «void *» used in arithmetic
    Selection.c:16: attention : pointer of type «void *» used in arithmetic
    Selection.c:18: attention : pointer of type «void *» used in arithmetic
    Selection.c:19: attention : pointer of type «void *» used in arithmetic
    Selection.c:19: attention : pointer of type «void *» used in arithmetic
    Selection.c:20: attention : pointer of type «void *» used in arithmetic
    Si quelqu'un pouvais m'aider à en résoudre ca serait sympathique.

    Merci d'avance.

  2. #2
    Rédacteur

    Avatar de millie
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    7 015
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2006
    Messages : 7 015
    Par défaut
    Le code source de qsort si ça peut t'aider :


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    /*-
     * Copyright (c) 1992, 1993
     *	The Regents of the University of California.  All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     * 1. Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     * 2. Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in the
     *    documentation and/or other materials provided with the distribution.
     * 3. All advertising materials mentioning features or use of this software
     *    must display the following acknowledgement:
     *	This product includes software developed by the University of
     *	California, Berkeley and its contributors.
     * 4. Neither the name of the University nor the names of its contributors
     *    may be used to endorse or promote products derived from this software
     *    without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     * SUCH DAMAGE.
     *
     * $FreeBSD: src/sys/libkern/qsort.c,v 1.10 1999/08/28 00:46:35 peter Exp $
     */
     
    #include <sys/libkern.h>
     
    typedef int		 cmp_t __P((const void *, const void *));
    static __inline char	*med3 __P((char *, char *, char *, cmp_t *));
    static __inline void	 swapfunc __P((char *, char *, int, int));
     
    #define min(a, b)	(a) < (b) ? a : b
     
    /*
     * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
     */
    #define swapcode(TYPE, parmi, parmj, n) { 		\
    	long i = (n) / sizeof (TYPE); 			\
    	register TYPE *pi = (TYPE *) (parmi); 		\
    	register TYPE *pj = (TYPE *) (parmj); 		\
    	do { 						\
    		register TYPE	t = *pi;		\
    		*pi++ = *pj;				\
    		*pj++ = t;				\
            } while (--i > 0);				\
    }
     
    #define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
    	es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
     
    static __inline void
    swapfunc(a, b, n, swaptype)
    	char *a, *b;
    	int n, swaptype;
    {
    	if(swaptype <= 1)
    		swapcode(long, a, b, n)
    	else
    		swapcode(char, a, b, n)
    }
     
    #define swap(a, b)					\
    	if (swaptype == 0) {				\
    		long t = *(long *)(a);			\
    		*(long *)(a) = *(long *)(b);		\
    		*(long *)(b) = t;			\
    	} else						\
    		swapfunc(a, b, es, swaptype)
     
    #define vecswap(a, b, n) 	if ((n) > 0) swapfunc(a, b, n, swaptype)
     
    static __inline char *
    med3(a, b, c, cmp)
    	char *a, *b, *c;
    	cmp_t *cmp;
    {
    	return cmp(a, b) < 0 ?
    	       (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a ))
                  :(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c ));
    }
     
    void
    qsort(a, n, es, cmp)
    	void *a;
    	size_t n, es;
    	cmp_t *cmp;
    {
    	char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
    	int d, r, swaptype, swap_cnt;
     
    loop:	SWAPINIT(a, es);
    	swap_cnt = 0;
    	if (n < 7) {
    		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
    			for (pl = pm; pl > (char *)a && cmp(pl - es, pl) > 0;
    			     pl -= es)
    				swap(pl, pl - es);
    		return;
    	}
    	pm = (char *)a + (n / 2) * es;
    	if (n > 7) {
    		pl = a;
    		pn = (char *)a + (n - 1) * es;
    		if (n > 40) {
    			d = (n / 8) * es;
    			pl = med3(pl, pl + d, pl + 2 * d, cmp);
    			pm = med3(pm - d, pm, pm + d, cmp);
    			pn = med3(pn - 2 * d, pn - d, pn, cmp);
    		}
    		pm = med3(pl, pm, pn, cmp);
    	}
    	swap(a, pm);
    	pa = pb = (char *)a + es;
     
    	pc = pd = (char *)a + (n - 1) * es;
    	for (;;) {
    		while (pb <= pc && (r = cmp(pb, a)) <= 0) {
    			if (r == 0) {
    				swap_cnt = 1;
    				swap(pa, pb);
    				pa += es;
    			}
    			pb += es;
    		}
    		while (pb <= pc && (r = cmp(pc, a)) >= 0) {
    			if (r == 0) {
    				swap_cnt = 1;
    				swap(pc, pd);
    				pd -= es;
    			}
    			pc -= es;
    		}
    		if (pb > pc)
    			break;
    		swap(pb, pc);
    		swap_cnt = 1;
    		pb += es;
    		pc -= es;
    	}
    	if (swap_cnt == 0) {  /* Switch to insertion sort */
    		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
    			for (pl = pm; pl > (char *)a && cmp(pl - es, pl) > 0;
    			     pl -= es)
    				swap(pl, pl - es);
    		return;
    	}
     
    	pn = (char *)a + n * es;
    	r = min(pa - (char *)a, pb - pa);
    	vecswap(a, pb - r, r);
    	r = min(pd - pc, pn - pd - es);
    	vecswap(pb, pn - r, r);
    	if ((r = pb - pa) > es)
    		qsort(a, r / es, es, cmp);
    	if ((r = pd - pc) > es) {
    		/* Iterate rather than recurse to save stack space */
    		a = pn - r;
    		n = r / es;
    		goto loop;
    	}
    /*		qsort(pn - r, r / es, es, cmp);*/
    }

    Avec un beau goto


    Une autre version :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    /* qsort.c
     * (c) 1998 Gareth McCaughan
     *
     * This is a drop-in replacement for the C library's |qsort()| routine.
     *
     * Features:
     *   - Median-of-three pivoting (and more)
     *   - Truncation and final polishing by a single insertion sort
     *   - Early truncation when no swaps needed in pivoting step
     *   - Explicit recursion, guaranteed not to overflow
     *   - A few little wrinkles stolen from the GNU |qsort()|.
     *   - separate code for non-aligned / aligned / word-size objects
     *
     * This code may be reproduced freely provided
     *   - this file is retained unaltered apart from minor
     *     changes for portability and efficiency
     *   - no changes are made to this comment
     *   - any changes that *are* made are clearly flagged
     *   - the _ID string below is altered by inserting, after
     *     the date, the string " altered" followed at your option
     *     by other material. (Exceptions: you may change the name
     *     of the exported routine without changing the ID string.
     *     You may change the values of the macros TRUNC_* and
     *     PIVOT_THRESHOLD without changing the ID string, provided
     *     they remain constants with TRUNC_nonaligned, TRUNC_aligned
     *     and TRUNC_words/WORD_BYTES between 8 and 24, and
     *     PIVOT_THRESHOLD between 32 and 200.)
     *
     * You may use it in anything you like; you may make money
     * out of it; you may distribute it in object form or as
     * part of an executable without including source code;
     * you don't have to credit me. (But it would be nice if
     * you did.)
     *
     * If you find problems with this code, or find ways of
     * making it significantly faster, please let me know!
     * My e-mail address, valid as of early 1998 and certainly
     * OK for at least the next 18 months, is
     *    gjm11@dpmms.cam.ac.uk
     * Thanks!
     *
     * Gareth McCaughan   Peterhouse   Cambridge   1998
     */
     
    #include <assert.h>
    #include <stdlib.h>
    #include <string.h>
     
    static char _ID[]="<qsort.c gjm 1.12 1998-03-19>";
     
    /* How many bytes are there per word? (Must be a power of 2,
     * and must in fact equal sizeof(int).)
     */
    #define WORD_BYTES sizeof(int)
     
    /* How big does our stack need to be? Answer: one entry per
     * bit in a |size_t|.
     */
    #define STACK_SIZE (8*sizeof(size_t))
     
    /* Different situations have slightly different requirements,
     * and we make life epsilon easier by using different truncation
     * points for the three different cases.
     * So far, I have tuned TRUNC_words and guessed that the same
     * value might work well for the other two cases. Of course
     * what works well on my machine might work badly on yours.
     */
    #define TRUNC_nonaligned	12
    #define TRUNC_aligned		12
    #define TRUNC_words		12*WORD_BYTES	/* nb different meaning */
     
    /* We use a simple pivoting algorithm for shortish sub-arrays
     * and a more complicated one for larger ones. The threshold
     * is PIVOT_THRESHOLD.
     */
    #define PIVOT_THRESHOLD 40
     
    typedef struct { char * first; char * last; } stack_entry;
    #define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;}
    #define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;}
    #define doLeft {first=ffirst;llast=last;continue;}
    #define doRight {ffirst=first;last=llast;continue;}
    #define pop {if (--stacktop<0) break;\
      first=ffirst=stack[stacktop].first;\
      last=llast=stack[stacktop].last;\
      continue;}
     
    /* Some comments on the implementation.
     * 1. When we finish partitioning the array into "low"
     *    and "high", we forget entirely about short subarrays,
     *    because they'll be done later by insertion sort.
     *    Doing lots of little insertion sorts might be a win
     *    on large datasets for locality-of-reference reasons,
     *    but it makes the code much nastier and increases
     *    bookkeeping overhead.
     * 2. We always save the shorter and get to work on the
     *    longer. This guarantees that every time we push
     *    an item onto the stack its size is <= 1/2 of that
     *    of its parent; so the stack can't need more than
     *    log_2(max-array-size) entries.
     * 3. We choose a pivot by looking at the first, last
     *    and middle elements. We arrange them into order
     *    because it's easy to do that in conjunction with
     *    choosing the pivot, and it makes things a little
     *    easier in the partitioning step. Anyway, the pivot
     *    is the middle of these three. It's still possible
     *    to construct datasets where the algorithm takes
     *    time of order n^2, but it simply never happens in
     *    practice.
     * 3' Newsflash: On further investigation I find that
     *    it's easy to construct datasets where median-of-3
     *    simply isn't good enough. So on large-ish subarrays
     *    we do a more sophisticated pivoting: we take three
     *    sets of 3 elements, find their medians, and then
     *    take the median of those.
     * 4. We copy the pivot element to a separate place
     *    because that way we can always do our comparisons
     *    directly against a pointer to that separate place,
     *    and don't have to wonder "did we move the pivot
     *    element?". This makes the inner loop better.
     * 5. It's possible to make the pivoting even more
     *    reliable by looking at more candidates when n
     *    is larger. (Taking this to its logical conclusion
     *    results in a variant of quicksort that doesn't
     *    have that n^2 worst case.) However, the overhead
     *    from the extra bookkeeping means that it's just
     *    not worth while.
     * 6. This is pretty clean and portable code. Here are
     *    all the potential portability pitfalls and problems
     *    I know of:
     *      - In one place (the insertion sort) I construct
     *        a pointer that points just past the end of the
     *        supplied array, and assume that (a) it won't
     *        compare equal to any pointer within the array,
     *        and (b) it will compare equal to a pointer
     *        obtained by stepping off the end of the array.
     *        These might fail on some segmented architectures.
     *      - I assume that there are 8 bits in a |char| when
     *        computing the size of stack needed. This would
     *        fail on machines with 9-bit or 16-bit bytes.
     *      - I assume that if |((int)base&(sizeof(int)-1))==0|
     *        and |(size&(sizeof(int)-1))==0| then it's safe to
     *        get at array elements via |int*|s, and that if
     *        actually |size==sizeof(int)| as well then it's
     *        safe to treat the elements as |int|s. This might
     *        fail on systems that convert pointers to integers
     *        in non-standard ways.
     *      - I assume that |8*sizeof(size_t)<=INT_MAX|. This
     *        would be false on a machine with 8-bit |char|s,
     *        16-bit |int|s and 4096-bit |size_t|s. :-)
     */
     
    /* The recursion logic is the same in each case: */
    #define Recurse(Trunc)				\
          { size_t l=last-ffirst,r=llast-first;	\
            if (l<Trunc) {				\
              if (r>=Trunc) doRight			\
              else pop				\
            }					\
            else if (l<=r) { pushLeft; doRight }	\
            else if (r>=Trunc) { pushRight; doLeft }\
            else doLeft				\
          }
     
    /* and so is the pivoting logic: */
    #define Pivot(swapper,sz)			\
      if (last-first>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare);\
      else {	\
        if (compare(first,mid)<0) {			\
          if (compare(mid,last)>0) {		\
            swapper(mid,last);			\
            if (compare(first,mid)>0) swapper(first,mid);\
          }						\
        }						\
        else {					\
          if (compare(mid,last)>0) swapper(first,last)\
          else {					\
            swapper(first,mid);			\
            if (compare(mid,last)>0) swapper(mid,last);\
          }						\
        }						\
        first+=sz; last-=sz;			\
      }
     
    #ifdef DEBUG_QSORT
    #include <stdio.h>
    #endif
     
    /* and so is the partitioning logic: */
    #define Partition(swapper,sz) {			\
      int swapped=0;				\
      do {						\
        while (compare(first,pivot)<0) first+=sz;	\
        while (compare(pivot,last)<0) last-=sz;	\
        if (first<last) {				\
          swapper(first,last); swapped=1;		\
          first+=sz; last-=sz; }			\
        else if (first==last) { first+=sz; last-=sz; break; }\
      } while (first<=last);			\
      if (!swapped) pop				\
    }
     
    /* and so is the pre-insertion-sort operation of putting
     * the smallest element into place as a sentinel.
     * Doing this makes the inner loop nicer. I got this
     * idea from the GNU implementation of qsort().
     */
    #define PreInsertion(swapper,limit,sz)		\
      first=base;					\
      last=first + (nmemb>limit ? limit : nmemb-1)*sz;\
      while (last!=base) {				\
        if (compare(first,last)>0) first=last;	\
        last-=sz; }					\
      if (first!=base) swapper(first,(char*)base);
     
    /* and so is the insertion sort, in the first two cases: */
    #define Insertion(swapper)			\
      last=((char*)base)+nmemb*size;		\
      for (first=((char*)base)+size;first!=last;first+=size) {	\
        char *test;					\
        /* Find the right place for |first|.	\
         * My apologies for var reuse. */		\
        for (test=first-size;compare(test,first)>0;test-=size) ;	\
        test+=size;					\
        if (test!=first) {				\
          /* Shift everything in [test,first)	\
           * up by one, and place |first|		\
           * where |test| is. */			\
          memcpy(pivot,first,size);			\
          memmove(test+size,test,first-test);	\
          memcpy(test,pivot,size);			\
        }						\
      }
     
    #define SWAP_nonaligned(a,b) { \
      register char *aa=(a),*bb=(b); \
      register size_t sz=size; \
      do { register char t=*aa; *aa++=*bb; *bb++=t; } while (--sz); }
     
    #define SWAP_aligned(a,b) { \
      register int *aa=(int*)(a),*bb=(int*)(b); \
      register size_t sz=size; \
      do { register int t=*aa;*aa++=*bb; *bb++=t; } while (sz-=WORD_BYTES); }
     
    #define SWAP_words(a,b) { \
      register int t=*((int*)a); *((int*)a)=*((int*)b); *((int*)b)=t; }
     
    /* ---------------------------------------------------------------------- */
     
    static char * pivot_big(char *first, char *mid, char *last, size_t size,
                            int compare(const void *, const void *)) {
      int d=(((last-first)/size)>>3)*size;
      char *m1,*m2,*m3;
      { char *a=first, *b=first+d, *c=first+2*d;
    #ifdef DEBUG_QSORT
    fprintf(stderr,"< %d %d %d\n",*(int*)a,*(int*)b,*(int*)c);
    #endif
        m1 = compare(a,b)<0 ?
               (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
             : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
      }
      { char *a=mid-d, *b=mid, *c=mid+d;
    #ifdef DEBUG_QSORT
    fprintf(stderr,". %d %d %d\n",*(int*)a,*(int*)b,*(int*)c);
    #endif
        m2 = compare(a,b)<0 ?
               (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
             : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
      }
      { char *a=last-2*d, *b=last-d, *c=last;
    #ifdef DEBUG_QSORT
    fprintf(stderr,"> %d %d %d\n",*(int*)a,*(int*)b,*(int*)c);
    #endif
        m3 = compare(a,b)<0 ?
               (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
             : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
      }
    #ifdef DEBUG_QSORT
    fprintf(stderr,"-> %d %d %d\n",*(int*)m1,*(int*)m2,*(int*)m3);
    #endif
      return compare(m1,m2)<0 ?
               (compare(m2,m3)<0 ? m2 : (compare(m1,m3)<0 ? m3 : m1))
             : (compare(m1,m3)<0 ? m1 : (compare(m2,m3)<0 ? m3 : m2));
    }
     
    /* ---------------------------------------------------------------------- */
     
    static void qsort_nonaligned(void *base, size_t nmemb, size_t size,
               int (*compare)(const void *, const void *)) {
     
      stack_entry stack[STACK_SIZE];
      int stacktop=0;
      char *first,*last;
      char *pivot=malloc(size);
      size_t trunc=TRUNC_nonaligned*size;
      assert(pivot!=0);
     
      first=(char*)base; last=first+(nmemb-1)*size;
     
      if (last-first>trunc) {
        char *ffirst=first, *llast=last;
        while (1) {
          /* Select pivot */
          { char * mid=first+size*((last-first)/size >> 1);
            Pivot(SWAP_nonaligned,size);
            memcpy(pivot,mid,size);
          }
          /* Partition. */
          Partition(SWAP_nonaligned,size);
          /* Prepare to recurse/iterate. */
          Recurse(trunc)
        }
      }
      PreInsertion(SWAP_nonaligned,TRUNC_nonaligned,size);
      Insertion(SWAP_nonaligned);
      free(pivot);
    }
     
    static void qsort_aligned(void *base, size_t nmemb, size_t size,
               int (*compare)(const void *, const void *)) {
     
      stack_entry stack[STACK_SIZE];
      int stacktop=0;
      char *first,*last;
      char *pivot=malloc(size);
      size_t trunc=TRUNC_aligned*size;
      assert(pivot!=0);
     
      first=(char*)base; last=first+(nmemb-1)*size;
     
      if (last-first>trunc) {
        char *ffirst=first,*llast=last;
        while (1) {
          /* Select pivot */
          { char * mid=first+size*((last-first)/size >> 1);
            Pivot(SWAP_aligned,size);
            memcpy(pivot,mid,size);
          }
          /* Partition. */
          Partition(SWAP_aligned,size);
          /* Prepare to recurse/iterate. */
          Recurse(trunc)
        }
      }
      PreInsertion(SWAP_aligned,TRUNC_aligned,size);
      Insertion(SWAP_aligned);
      free(pivot);
    }
     
    static void qsort_words(void *base, size_t nmemb,
               int (*compare)(const void *, const void *)) {
     
      stack_entry stack[STACK_SIZE];
      int stacktop=0;
      char *first,*last;
      char *pivot=malloc(WORD_BYTES);
      assert(pivot!=0);
     
      first=(char*)base; last=first+(nmemb-1)*WORD_BYTES;
     
      if (last-first>TRUNC_words) {
        char *ffirst=first, *llast=last;
        while (1) {
    #ifdef DEBUG_QSORT
    fprintf(stderr,"Doing %d:%d: ",
            (first-(char*)base)/WORD_BYTES,
            (last-(char*)base)/WORD_BYTES);
    #endif
          /* Select pivot */
          { char * mid=first+WORD_BYTES*((last-first) / (2*WORD_BYTES));
            Pivot(SWAP_words,WORD_BYTES);
            *(int*)pivot=*(int*)mid;
          }
    #ifdef DEBUG_QSORT
    fprintf(stderr,"pivot=%d\n",*(int*)pivot);
    #endif
          /* Partition. */
          Partition(SWAP_words,WORD_BYTES);
          /* Prepare to recurse/iterate. */
          Recurse(TRUNC_words)
        }
      }
      PreInsertion(SWAP_words,(TRUNC_words/WORD_BYTES),WORD_BYTES);
      /* Now do insertion sort. */
      last=((char*)base)+nmemb*WORD_BYTES;
      for (first=((char*)base)+WORD_BYTES;first!=last;first+=WORD_BYTES) {
        /* Find the right place for |first|. My apologies for var reuse */
        int *pl=(int*)(first-WORD_BYTES),*pr=(int*)first;
        *(int*)pivot=*(int*)first;
        for (;compare(pl,pivot)>0;pr=pl,--pl) {
          *pr=*pl; }
        if (pr!=(int*)first) *pr=*(int*)pivot;
      }
      free(pivot);
    }
     
    /* ---------------------------------------------------------------------- */
     
    extern void qsortG(void *base, size_t nmemb, size_t size,
               int (*compare)(const void *, const void *)) {
     
      if (nmemb<=1) return;
      if (((int)base|size)&(WORD_BYTES-1))
        qsort_nonaligned(base,nmemb,size,compare);
      else if (size!=WORD_BYTES)
        qsort_aligned(base,nmemb,size,compare);
      else
        qsort_words(base,nmemb,compare);
    }

  3. #3
    Membre Expert
    Avatar de hiko-seijuro
    Profil pro
    Inscrit en
    Mai 2004
    Messages
    2 011
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France

    Informations forums :
    Inscription : Mai 2004
    Messages : 2 011
    Par défaut
    LE fait d'utiliser un void * t'enleves la possibilité d'utiliser l'arithmétique des pointeurs. Tu ne peux donc pas faire

  4. #4
    Expert éminent
    Avatar de Emmanuel Delahaye
    Profil pro
    Retraité
    Inscrit en
    Décembre 2003
    Messages
    14 512
    Détails du profil
    Informations personnelles :
    Âge : 68
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Retraité

    Informations forums :
    Inscription : Décembre 2003
    Messages : 14 512
    Par défaut
    Citation Envoyé par bleach1234
    Voici les warnings générés :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Selection.c:16: attention : pointer of type «void *» used in arithmetic
    C'est normal. void* ne permet pas l'arithmétique des pointeurs. Si tu sais ce que tu fais, tu peux te servir de la valeur du void* pour initialiser un pointeur local du bon type (char* ou unsigned char *, par exemple).
    Ensuite, tu pourras utiliser l'arithmétique des pointeurs comme tu veux. Je n'ai pas regardé la fonction en détail, mais je rappelle l'existence de la fonction memcpy()...

    EDIT : J'ai quand même regardé ton code, et il ne génère pas les warnings annoncés. C'est le bon code ?

    Ceci compile sans problèmes. Tu es sûr que tu compiles en C et non en C++ ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    void tri (void *tableau, size_t nb_elements, size_t taille_elements,
              int (*comp) (const void *, const void *))
    {
       size_t max, i;
       void *x = malloc (taille_elements);
       while (nb_elements > 1)
       {
          max = 0;
          for (i = 1; i < nb_elements; i++)
             if (comp
                 (tableau + (taille_elements * i),
                  tableau + (taille_elements * max)) > 0)
                max = i;
          memcpy (x, tableau + (taille_elements * max), taille_elements);
          memcpy (tableau + (taille_elements * max),
                  tableau + (taille_elements * (nb_elements - 1)),
                  taille_elements);
          memcpy (tableau + (taille_elements * (nb_elements - 1)), x,
                  taille_elements);
          nb_elements--;
       }
       free (x);
    }
    Attention, l'indentation automatique révèle peut être un problème d'absence de {}.

  5. #5
    gl
    gl est déconnecté
    Rédacteur

    Homme Profil pro
    Inscrit en
    Juin 2002
    Messages
    2 165
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Juin 2002
    Messages : 2 165
    Par défaut
    Citation Envoyé par Emmanuel Delahaye
    EDIT : J'ai quand même regardé ton code, et il ne génère pas les warnings annoncés. C'est le bon code ?
    tableau etant void*, les expressions du type "tableau+(taille_elements*max)" dans son code (utilise par exemple en parametres des memcpy()) posent bien probleme.

  6. #6
    Expert confirmé

    Inscrit en
    Novembre 2005
    Messages
    5 145
    Détails du profil
    Informations forums :
    Inscription : Novembre 2005
    Messages : 5 145
    Par défaut
    Citation Envoyé par Emmanuel Delahaye
    EDIT : J'ai quand même regardé ton code, et il ne génère pas les warnings annoncés. C'est le bon code ?

    Ceci compile sans problèmes. Tu es sûr que tu compiles en C et non en C++ ?
    L'arithmétique sur les void* est une extension de gcc. Je ne résiste pas:
    Citation Envoyé par gcc
    gcc-4.1 -std=c89 -pedantic-errors -c emmanuel.c
    emmanuel.c: In function 'tri':
    emmanuel.c:15: error: pointer of type 'void *' used in arithmetic
    emmanuel.c:16: error: pointer of type 'void *' used in arithmetic
    emmanuel.c:18: error: pointer of type 'void *' used in arithmetic
    emmanuel.c:19: error: pointer of type 'void *' used in arithmetic
    emmanuel.c:20: error: pointer of type 'void *' used in arithmetic
    emmanuel.c:22: error: pointer of type 'void *' used in arithmetic

    Compilation exited abnormally with code 1 at Sun Nov 5 17:15:14

  7. #7
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2006
    Messages
    52
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2006
    Messages : 52
    Par défaut
    Bonsoir,

    Merci pour vos réponses, pour reuissir a enlever ces warnings ma seule solution était de caster par un (char *)

    Exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    comp((char *)tableau + (taille_elements * i), (char *)tableau + (taille_elements * max))
    Mais cela implique que je ne pourrais utiliser d'autre type O___o

    En espèrant trouver une autre solution ^_^

  8. #8
    Expert éminent
    Avatar de Médinoc
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Septembre 2005
    Messages
    27 395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2005
    Messages : 27 395
    Par défaut
    Oui, il faut passer par un char* pour faire l'arithmétique de pointeurs.
    Mais uniquement en interne: La fonction callback de comparaison n'a pas à le savoir et prend quand même des void* en paramètre...
    SVP, pas de questions techniques par MP. Surtout si je ne vous ai jamais parlé avant.

    "Aw, come on, who would be so stupid as to insert a cast to make an error go away without actually fixing the error?"
    Apparently everyone.
    -- Raymond Chen.
    Traduction obligatoire: "Oh, voyons, qui serait assez stupide pour mettre un cast pour faire disparaitre un message d'erreur sans vraiment corriger l'erreur?" - Apparemment, tout le monde. -- Raymond Chen.

  9. #9
    Nouveau candidat au Club
    Profil pro
    Inscrit en
    Décembre 2003
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2003
    Messages : 2
    Par défaut
    Mais cela implique que je ne pourrais utiliser d'autre type.
    Non, pas du tout, le fait de passer par un char * est juste là pour pouvoir utiliser une opération arithmétique sur un pointeur.

    Comme un char est la plus petite unité adressable par un programme C, c'est plutôt normal. De plus, comme tu passe la taille du type (qui est donc exprimé en la taille d'un char), l'opération est tout à fait naturelle et s'applique donc à n'importe quel type de donnée.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Fonction qsort, l'affichage
    Par Cannot dans le forum Débuter
    Réponses: 2
    Dernier message: 04/09/2010, 18h55
  2. la fonction qsort
    Par pipip dans le forum Débuter
    Réponses: 2
    Dernier message: 27/10/2009, 22h41
  3. Problème fonction QSORT
    Par antoine_59 dans le forum C
    Réponses: 2
    Dernier message: 29/12/2008, 11h27
  4. fonction qsort ()
    Par kevinou55 dans le forum Débuter
    Réponses: 2
    Dernier message: 06/12/2008, 16h59
  5. Utilisation de la fonction qsort
    Par Jsmeline dans le forum C
    Réponses: 8
    Dernier message: 28/01/2005, 12h40

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo