1

J'ai besoin d'un algorithme de tri efficace, est ce que quelqu'un pourrait me donner quelques noms d'algorithmes svp et me les expliquer?! non pas avec un algo mais m'en donner le principe?!

J'en ai trouvé un mais il est pas tellement linéaire et c'est plutot embettant.

Il doit etre capable de trier un tableau de tableaux de bytes le plus rapidement possible, ou plutot le plus efficacement possible tongue

vous pouvez l'expliquer avec un tableau d'entier si vous voulez pour simplifier smile

2

PaXaL - posté 2001-10-06 07:24:49

Tri par selection
On cherche le plus petit élément de t[1] à t[n] et on l'échange avec t[1]; puis on cherche le plus petit élement de t[1] à t[n] que l'on échange avec t[1] et ainsi de suite.
Complexité en n^2/2

Tri par insertion
On trie le tableau de proche en proche: si le tableau est trié de 1 à k, alors oin insère l'élément (k+1) parmi les k premiers; ainsi le tableau est trié jusqu'à l'élément k+1.
Complexité:
- n^2/2 dans le pire des cas
- n dans le meilleur des cas
- n^2/4 en moyenne

Tri Fusion (merge sort)
Si le tableau a une taille supérieure à 1, on le divise en deux sous-tableaux de taille E(n/2) et E((n+1)/2), que l'on trie récursivement, puis que l'on fusionne.
Complexité en n.log n

Tri Rapide (quick sort)
On trie le tableau grâce à un pivot: on prend x le premier élément et on réarrange le tableau en deux classes: Ai > x et Ai <= x. Chaque sous tableau est alors trié récursivement.
Complexité :
- n.log n dans le meilleur des cas
- n^2 dans le pire des cas
- n.log n en moyenne




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

http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html

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

http://www.whisqu.se/per/docs/general17.htm

http://www.whisqu.se/per/docs/general18.htm

http://www.whisqu.se/per/docs/general19.htm

http://www.whisqu.se/per/docs/general20.htm

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

http://www.alrj.org/docs/algo/bsort.php

3

heu, voila le premier lien mort :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0043)http://www.whisqu.se/per/docs/general18.htm -->
<HTML><HEAD><TITLE>Elementary Sorting Techniques</TITLE>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<META content="MSHTML 6.00.2600.0" name=GENERATOR></HEAD>
<BODY text=#000000 vLink=#666699 aLink=#000000 link=#666699 bgColor=#ffffff>
<TABLE cellSpacing=0 cellPadding=5 width=640 bgColor=#666699 border=0>
  <TBODY>
  <TR>
    <TD align=left width="90%" bgColor=#666699><FONT face=arial 
      color=#ffffff><B>Elementary Sorting Techniques</B></FONT> </TD>
    <TD align=right bgColor=#000000><A 
      href="http://www.whisqu.se/per/docs/general.htm"><FONT face=arial 
      color=#ffffff><B>Back</B></A></FONT></TD></TR></TBODY></TABLE>
<CENTER><BR>
<CENTER>
<TABLE cellSpacing=0 cellPadding=10 border=0>
  <TBODY>
  <TR>
    <TD><BR><BR><PRE>

                       Elementary Sorting Algorithms

There is a suprisingly diverse collection of algorithms that have been
developed to solve the apparently simple problem of "Sorting".

The general sorting problem is simple enough to describe: Given an
initially unordered array of N records, with one field distinguished as the
key, rearrange the records so they are sorted into increasing (or
decreasing) order, according to each record's key.

Sorting algorithms are used in all kinds of applications and are necessary,
for instance, if we plan to use efficient searching algorithms like Binary
Search or Interpolation Search, since these require their data to be
sorted.

Sorting algorithms are often subdivided into "elementary" algorithms that
are simple to implement compared to more complex algorithms that, while
more efficient, are also more difficult to understand, implement, and
debug.

It is not always true that the more complex algorithms are the preferred
ones. Elementary algorithms are generally more appropriate in the following
situations:

   * less than 100 values to be sorted
   * the values will be sorted just once
   * special cases such as:
        o the input data are "almost sorted"
        o there are many equal keys

In general, elementary sorting methods require O(N2) steps for N random key
values. The more complex methods can often sort the same data in just O(N
log N) steps. Although it is rather difficult to prove, it can be shown
that roughly N log N comparisons are required, in the general case.

Internal vs. External Sorting

Normally, when considering a sorting problem, we will assume that the
number of records to be sorted is small enough that we can fit the entire
data set in the computer's memory (RAM) all at once. When this is true, we
can make use of an internal sorting algorithm, which assumes that any key
or record can be accessed or moved at any time. That is, we have "random
access" to the data.

Sometimes, when sorting an extremely large data set such as Canada's Census
Data, there are simply too many records for them to all fit in memory at
once. In this case, we have to resort to external sorting algorithms that
don't assume we have random access to the data. Instead, these algorithms
assume the data is stored on magnetic tapes or disks and only portions of
the data will fit in memory. These algorithms use "sequential access" to
the data and proceed by reading in, processing, and writing out blocks of
records at a time. These partially sorted blocks need to be combined or
merged in some manner to eventually sort the entire list.

Stability

When a sorting algorithm is applied to a set of records, some of which
share the same key, there are several different orderings that are all
correctly sorted. If the ordering of records with identical keys is always
the same as in the original input, then we say that the sorting algorithm
used is "stable".

This property can be useful. For instance, consider sorting a list of
student records alphabetically by name, and then sorting the list again,
but this time by letter grade in a particular course. If the sorting
algorithm is stable, then all the students who got "A" will be listed
alphabetically.

Stability is a difficult property to achieve if we also want our sorting
algorithm to be efficient.

Indirect Sorting

One final issue to keep in mind when implementing a sorting algorithm is
the size of the records themselves. Many sorting algorithms move and
interchange records in memory several times before they are moved into
their final sorted position. For large records, this can add up to lots of
execution time spent simply copying data.

A popular solution to this problem is called "indirect sorting". The idea
is to sort the indices of the records, rather than the records themselves.
---------------------------------------------------------------------------


          
</PRE></TD></TR></TBODY></TABLE></CENTER></CENTER></BODY></HTML>

4

le 2eme

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0043)http://www.whisqu.se/per/docs/general20.htm -->
<HTML><HEAD><TITLE>Comparison Of Sorting Algorithms</TITLE>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<META content="MSHTML 6.00.2600.0" name=GENERATOR></HEAD>
<BODY text=#000000 vLink=#666699 aLink=#000000 link=#666699 bgColor=#ffffff>
<TABLE cellSpacing=0 cellPadding=5 width=640 bgColor=#666699 border=0>
  <TBODY>
  <TR>
    <TD align=left width="90%" bgColor=#666699><FONT face=arial 
      color=#ffffff><B>Comparison Of Sorting Algorithms</B></FONT> </TD>
    <TD align=right bgColor=#000000><A 
      href="http://www.whisqu.se/per/docs/general.htm"><FONT face=arial 
      color=#ffffff><B>Back</B></A></FONT></TD></TR></TBODY></TABLE>
<CENTER><BR>
<CENTER>
<TABLE cellSpacing=0 cellPadding=10 border=0>
  <TBODY>
  <TR>
    <TD><BR><BR><PRE>

                      Comparison of Sorting Algorithms

The following table summarizes the basic strategies used in various sorting
algorithms, and lists the algorithms that use these strategies.

     Comparison-Based Sorting Methods
          Transposition (exchange adjacent values)
               Bubble Sort **
          Priority Queue (select largest value)
               Selection Sort **
               Heap Sort
          Insert and Keep Sorted
               Insertion Sort **
               Tree Sort
          Diminishing Increment
               Shell Sort
          Divide &amp; Conquer
               Quicksort
               Merge Sort
     Address-Calculation Sorting Methods
          Radix Sort

Algorithms marked with ** have been discussed in class. Implementations of
some of these algorithms are available on the Pascal Page.

The diagrams below may help you develop an intuitive sense of how the
algorithms work. The vertical axis is the position within the array and the
horizontal axis is time. Values within the array are represented by small
squares with differing brightness. The goal of the algorithm is to sort the
values from darkest to lightest. In each diagram, the input array is
represented by a vertical column on the left, with an random assortment of
brightess values. (Click on an image to see a larger version.)

  [bubble sort]     [selection sort]     [insertion sort]     [quicksort]
      bubble            selection            insertion         quicksort

Bubble Sort exchanges adjacent values so lighter ones "bubble up" towards
the top, and darker ones "sink down" towards the bottom. Selection Sort
minimizes exchanges by scanning the unsorted portion to find the largest
remaining value on each iteration. Insertion Sort is familiar to anyone who
plays cards. It works by taking the next value from the unsorted portion
and inserting it into the already sorted portion of the array. Of these
three, Insertion Sort is the most efficient, on average, but Selection Sort
is preferred when the records are large. Bubble Sort is never preferred.
(Quicksort will be discussed later in this course.)

The following table summarizes what we have learned about the relative
efficiency of various sorting algorithms.

     Bubble Sort (version discussed in class)
          best case:
               about N comparisons, 0 exchanges,
               (input already sorted)
          worst case:
               about N^2 comparisons, N^2 exchanges,
               (input sorted in reverse order)
          average case:
               quite close to worst case (difficult to analyze)
          notes:
               Very inefficient and should never be used. Uses an
               excessive and unnecessary number of exchanges.

     Bubble Sort (version in textbook)
          best case:
               about N^2/2 comparisons, 0 exchanges,
               (input already sorted)
          worst, average cases:
               about N^2/2 comparisons, N^2/2 exchanges

     Selection Sort
          all cases:
               about N^2/2 comparisons, N exchanges
          notes:
               minimizes the number of exchanges;
               execution time quite insensitive to original ordering
               of input data.

     Insertion Sort
          best case:
               about N comparisons, 0 moves,
               (input already sorted)
          worst case:
               about N^2/2 comparisons, N^2/2 moves,
               (input sorted in reverse order)
          average case:
               about N^2/4 comparisons, N^2/4 moves
          notes:
               very efficient when input is "almost sorted";
               moving a record is about half the work of exchanging
               two records, so average case is equivalent to roughly
               N^2/8 exchanges.

---------------------------------------------------------------------------


          
</PRE></TD></TR></TBODY></TABLE></CENTER></CENTER></BODY></HTML>

5

et le 3eme

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0043)http://www.whisqu.se/per/docs/general19.htm -->
<HTML><HEAD><TITLE>Shell Sorting</TITLE>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<META content="MSHTML 6.00.2600.0" name=GENERATOR></HEAD>
<BODY text=#000000 vLink=#666699 aLink=#000000 link=#666699 bgColor=#ffffff>
<TABLE cellSpacing=0 cellPadding=5 width=640 bgColor=#666699 border=0>
  <TBODY>
  <TR>
    <TD align=left width="90%" bgColor=#666699><FONT face=arial 
      color=#ffffff><B>Shell Sorting</B></FONT> </TD>
    <TD align=right bgColor=#000000><A 
      href="http://www.whisqu.se/per/docs/general.htm"><FONT face=arial 
      color=#ffffff><B>Back</B></A></FONT></TD></TR></TBODY></TABLE>
<CENTER><BR>
<CENTER>
<TABLE cellSpacing=0 cellPadding=10 border=0>
  <TBODY>
  <TR>
    <TD><BR><BR><PRE>

                                 Shell Sort

Shell Sort is the first sorting algorithm we'll look at that requires fewer
than O(N2) comparisons and exchanges, on average. Although it is easy to
develop an intuitive sense of how this algorithm works, it is very
difficult to analyze its execution time.

Shell Sort is really just an extension of Insertion Sort, with two
observations in mind:

   * Insertion Sort is efficient if the input is "almost sorted".
   * Insertion Sort is inefficient, on average, because it moves values
     just one position at a time.

Shell Sort is similar to Insertion Sort, but it works by taking "bigger
steps" as it rearranges values, gradually decreasing the step size down
towards one. In the end, Shell Sort performs a regular Insertion Sort but
by then, the array of data is guaranteed to be "almost sorted".

Consider a small value that is initially stored in the wrong end of the
array. Using Insertion Sort, it will take roughly N comparisons and
exchanges to move this value all the way to the other end of the array.
With Shell Sort, we'll first move values using giant step sizes, so a small
value will move a long way towards it's final position, with just a few
comparisons and exchanges.

It's easiest to understand how Shell Sort works by looking at a specific
example. The table below shows what happens when we apply a version of
Insertion Sort that has been modified to use a step size of 4. (An asterisk
* indicates a value that has been exchanged.)

                               step size = 4
                 index input i=5i=6 i=7 i=8 i=9i=10 output
                    10    20                    *26     26
                     9    28                *29         29
                     8    21            *22             22
                     7    25         25                 25
                     6    23    *26             *23     23
                     5    27 *29            *28         28
                     4    22            *21             21
                     3    24         24                 24
                     2    26    *23             *20     20
                     1    29 *27             27         27

As you can see, with a relatively small number of comparisons and
exchanges, smaller values (such as 20, 21) and larger values (such as 29)
have been moved a lot closer to their final sorted position.

Now that the array is a lot closer to being "almost sorted", we can apply
the usual Insertion Sort algorithm, with a step size of 1. In general, we
expect this final step to be quite efficient, although that may not be
apparent in this small example.

                               step size = 1
           index input i=2 i=3i=4 i=5 i=6 i=7i=8 i=9 i=10 output
              10    26                                *29     29
               9    29                            29  *28     28
               8    22                       *28  28  *27     27
               7    25                    *28*27      *26     26
               6    23                *28 *27*25       25     25
               5    28             28 *27 *25*24              24
               4    21        *27  27 *24  24*23              23
               3    24     *27*24     *23    *22              22
               2    20 *27 *24*21      21     21              21
               1    27 *20  20 20                             20

In general case, when the number of values to be sorted can be very large,
Shell Sort uses a sequence of diminishing step sizes. One popular sequence
is: ..., 1093, 364, 121, 40, 13, 4, 1, and this tends to work well in
practice.

A summary of the Shell Sort algorithm is given below. (A complete
implementation is given on the Pascal page.)

     -----------------------------------------------------------------

     procedure shellsort;
       var
         step        : integer;
       begin
         step := 1;
         repeat
           step := 3*step+1
         until step &gt; n;

         repeat
           step := step div 3;

           { do insertion sort, ... }
           { ... with specified step size }

         until step = 1;
       end;

     -----------------------------------------------------------------

The diagram below may help you develop an intuitive sense of how Shell Sort
actually works. The vertical axis is the position within the array and the
horizontal axis is time. Values in the array are represented by small
squares with differing brightness. The goal of the algorithm is to sort the
values from darkest to lightest. The input array is shown as the vertical
column on the left, with an initially random assortment of brightness
values. In this example, there are 64 values, and the step size sequence
is: 40, 13, 4, 1.

                               [shell sort]
                                 shellsort

In the diagram above, a new "snapshot" of the partially sorted array was
output every time another N comparisons were completed, so the work done by
Shell Sort is roughly proportional to the area. Since the diagram is a
tall, thin rectangle, you can immediately see that significantly fewer than
N2 comparisons were needed for this example.

In general, Shell Sort is very difficult to analyze. In fact, no one has
been able to figure out a precise description of the execution time of
Shell Sort. For the implementation given above, it has been conjectured
that when N is large, the execution time is rougly proportional to N log2 N
or N1.25, but no one has been able to prove it.

---------------------------------------------------------------------------
                             [*] CompSci-1MD3


          
</PRE></TD></TR></TBODY></TABLE></CENTER></CENTER></BODY></HTML>

6

ah c'est cool merci smile

si vous en avez d'autre ou si vous savez bien expliquer hesitez pas tongue

7

je rappelle que j'avais fait un truc sur ti-fr ... ca s'appelle un tuto. et que dedans y'a des tris ... enfin j'dis ca ... peut etre que c mal expliqué et donc fo me le dire qd meme
avatar
Il n'a pas de mots
Décrire son mépris
Perdre les rênes
Il a perdu la foi

8

pt1, le tri fusion est le plus efficace! j'hallucine!
il est pourtant hyper simple!
c'est marrant, c'est le premier que j'ai appris a la fac, tant mieux tongue

faut que je retrouve les sources, en plus ct en scheme!

9

Je ne m'en sors pas: j'explique le pb:
Le but est de trier un tableau de chaines de caractères le plus rapidement possible!!!
Par tri fusion et compagnons recursifs, c'est pas possible, car aboutira a un outofmemory, vu que la ram est deja occupé au maximum!
Commen tfaire un algo rapide sans recursivité et sans copie de tableaux! juste des mouvements dans le tableau!
Cours et tutos Asm: http://membres.lycos.fr/sirryl

10



http://gpreuvot.free.fr/TB11.doc


Rapport : Dossier Etude technique sur les tris.


PARTIE 1 : PRÉSENTATION ET PROGRAMMATION DES TRIS. 2
Le tri par extraction (ou sélection) du minimum (sélection sort). 2
Le tri par insertion (insertion sort). 4
Le tri par bulles (bubble sort) 5
Le tri shell (shellsort) 6
PARTIE 2 : MESURE DE PERFORMANCES ET VÉRIFICATION EXPÉRIMENTALE. 9
PARTIE 3 : RECHERCHE DES CAS FAVORABLES ET DÉFAVORABLES 9
PARTIE 4 : CONCLUSION 9
Boss et reponsable des archives de www.ti-fr.org

Donnons une majorité à Jacques Chirac
-------------------------------------------------------------
Pour donner une majorité à Jacques Chirac : le site de l'Union pour la Majorité Présidentielle
www.u-m-p.org

-------------------------------------------------------------

11

Boss et reponsable des archives de www.ti-fr.org

Donnons une majorité à Jacques Chirac
-------------------------------------------------------------
Pour donner une majorité à Jacques Chirac : le site de l'Union pour la Majorité Présidentielle
www.u-m-p.org

-------------------------------------------------------------

12

>Paxal: utilise des ptrs ver des sous chaines, pour creer des listes, puis classe ta liste par tri fusion.

13

Le plus efficace reste le tri shell ( dans le rapport j'ai els teste sour turbo profiler ...)

en fait ca depant de ce que tu veut faire si il y a enormelemnt de chosse utilis ele tri sheel sinon le tri fusion
Boss et reponsable des archives de www.ti-fr.org

Donnons une majorité à Jacques Chirac
-------------------------------------------------------------
Pour donner une majorité à Jacques Chirac : le site de l'Union pour la Majorité Présidentielle
www.u-m-p.org

-------------------------------------------------------------

14

Paxal a écrit :
Je ne m'en sors pas: j'explique le pb:
Le but est de trier un tableau de chaines de caractères le plus rapidement possible!!!
Par tri fusion et compagnons recursifs, c'est pas possible, car aboutira a un outofmemory, vu que la ram est deja occupé au maximum! Commen tfaire un algo rapide sans recursivité et sans copie de tableaux! juste des mouvements dans le tableau!


Utilise un QuickSort.
Ou, si le QuickSort ne te convient pas, un ShellSort, mais c'est probablement plus lent.
avatar
Mes news pour calculatrices TI: Ti-Gen
Mes projets PC pour calculatrices TI: TIGCC, CalcForge (CalcForgeLP, Emu-TIGCC)
Mes chans IRC: #tigcc et #inspired sur irc.freequest.net (UTF-8)

Liberté, Égalité, Fraternité

15

C'est bon, j'ai fait un quicksort, mais bon ce qui me chagrine un peu, c'est que c'est recursif! J'aime pas la recursivite, donc est-ce qu'il est possible de le rendre iteratif?
perso, j'ai pas troué sad

16

Ba oui tte fonction recursive peut etre ecrite en itératif.
Le plus simple serai de faire une variable qui simulerai la pile mais bon je e vois pas l'intéret.
Et pour tt dire, je vais prendre l'exemple de Hanoi : 3 lignes en recursif (et presque comprehensible) contre un 20aine en itéraif et partiquement incomprehensible.
Le recursif ca me plait bien moi.

17

le récursif, c'est beau !

18

Si vous voulez un algorithme de tri itératif, prenez un ShellSort. C'est ce qu'utilise la fonction qsort de TIGCCLIB.
avatar
Mes news pour calculatrices TI: Ti-Gen
Mes projets PC pour calculatrices TI: TIGCC, CalcForge (CalcForgeLP, Emu-TIGCC)
Mes chans IRC: #tigcc et #inspired sur irc.freequest.net (UTF-8)

Liberté, Égalité, Fraternité

19

Je croyais que je qsort devait etre un tri rapide?!

20

un algo recursif est génralement - rapide qu'un itératif. voilà pkoi. (dépose des args sur la pile, appel de la fn, etc...)

21

freka
a écrit : Je croyais que je qsort devait etre un tri rapide?!

En effet, en théorie qsort devrait être un QuickSort (d'où le nom). Mais selon Zeljko le ShellSort est beaucoup plus petit et n'est pas tellement plus lent que le QuickSort sur le genre de tableaux qu'on peut rencontrer sur TI-89/92+ (qui sont tous de taille relativement petite).
Le ShellSort m'a d'ailleurs l'air d'être le plus compact parmi les techniques de tri en moins de O(n²) (attention j'ai bien dit "m'a l'air" - je pourrais me tromper!), donc étant un défenseur de l'optimisation en taille, je ne peux que le recommander.
avatar
Mes news pour calculatrices TI: Ti-Gen
Mes projets PC pour calculatrices TI: TIGCC, CalcForge (CalcForgeLP, Emu-TIGCC)
Mes chans IRC: #tigcc et #inspired sur irc.freequest.net (UTF-8)

Liberté, Égalité, Fraternité

22

J'ai lu sur une doc, que le quicksort, peut etre assisté par un tri par insertion quand la taille est inférieure a 8 ou 9, qui dans ce cas est plus rapide.
ENfin c'est vrai que dans un programme ti il vaut mieux utiliser les plus petit en octets, mais vu ce que j'ai vu, on ne peu pas dire que les quicksort soit tres gros!

Ce qui m'embete c'est qu'il est pas tres rapide non plus pour ce que je veux tongue
puisqu'il faut comprarer des chaines, ce qui devient tres long justement, c'est de les comparer, puisque le classement ne met presque pas de temps !, enfin le tris par insertion etait 100 fois pire, sur un tableau de chaine de 5000 * 5000 octets

23

moi g ça pour trier des nombres d'un tbl en ordre croissant. Il suffie d'utiliser strcmp():

void bshort(short *start, short *end)
{
int i,k;
for(i=end-start; i!=0 ; i--)
for(k=0; k<i; k++)
if( start[k] > start[k+1])
swapshort(&start[k],&start[k+1]); //fonction qui échange les 2 éléments de place
}

//----------------------------------------

void swapshort(short *x, short *y)
{
short buffer;
buffer=*x;
*x=*y;
*y=buffer;
}

24

"Trier" se dit "sort" en anglais, pas "short"!
avatar
Mes news pour calculatrices TI: Ti-Gen
Mes projets PC pour calculatrices TI: TIGCC, CalcForge (CalcForgeLP, Emu-TIGCC)
Mes chans IRC: #tigcc et #inspired sur irc.freequest.net (UTF-8)

Liberté, Égalité, Fraternité

25

lol wink

26

Oué parceque QuickShort c''est tout autre chose. C'est un calbute rapide à mettre.

Alors c'est sûr que si on l'écrit mal la discussion devient incompréhensible... "mon calbute est moins performant que le tiens" picol
avatar
Un site complet sur lequel vous trouverez des programmes et des jeux pour votre calculatrice TI 89 / Titanium / 92+ / Voyage 200 : www.ti-fr.com.
Quelques idées personnelles ici.

27

Il existe un algorithme de tri, dont j'ai oublié le nom, et j'ai la flemme d'aller chercher mon "Algorithmes en C" en bas, qui est très efficace (quasi-linéaire, même), pour des clés peu diverses.

Par "clés", j'entends les éléments à trier.

Ca marche en gros comme ça (les détails, je les ai oubliés...) :
- on alloue un tableau d'entiers de la taille du nombre de clés différentes. Par exemple, si tu tries des bytes, tu alloues 256 entiers.
- on parcourt le tableau des données sources de gauche à droite... on compte le nombre d'occurences de chaque clé.
- ensuite, on utilise le tableau des occurences pour remplir le tableau source, et le tour est joué.

C'est valable si (taille de la chaîne) >> (nombre de clés différentes) et que (nombre de clés) << (espace mémoire)...

Je crois qu'une optimisation importante de l'algo est encore possible.

28

MadKeyboard a écrit :
Il existe un algorithme de tri, dont j'ai oublié le nom, et j'ai la flemme d'aller chercher mon "Algorithmes en C" en bas, qui est très efficace (quasi-linéaire, même), pour des clés peu diverses.

Par "clés", j'entends les éléments à trier.

Ca marche en gros comme ça (les détails, je les ai oubliés...) :
- on alloue un tableau d'entiers de la taille du nombre de clés différentes. Par exemple, si tu tries des bytes, tu alloues 256 entiers.
- on parcourt le tableau des données sources de gauche à droite... on compte le nombre d'occurences de chaque clé.
- ensuite, on utilise le tableau des occurences pour remplir le tableau source, et le tour est joué.

C'est valable si (taille de la chaîne) >> (nombre de clés différentes) et que (nombre de clés) << (espace mémoire)...
Je crois qu'une optimisation importante de l'algo est encore possible.


tri par comptage ?

29

MadKeyboard, oui, j'utilise cet algo deja, mais il n'est pas utilisable dans toutes les situations!en l'occurence il me sert a trier par exemple une chaine de caractères wink, c'est vrai que c'est rapide, mais par exemple sur un talbeua de chaine de caractère, ca ne serta rien c mort

30

voila un tri par insertion que j'ai fait pour classer des tableaux de chaines de caractères :
char **tab

void Str_Insertion(char **tab, int taille)
{
int i = 1, j, k;
char *temp;
while (i < taille)
{
j = i - 1;
if (strCmp(tab[j], tab[i]) < 0)
{
temp = (char *) tab[i];
while (j >= 0 && strCmp(tab[j], temp) < 0) tab[j+1] = (char *) tab[j--];
tab[j+1] = (char *) temp;
}
else i++;
}
}

mais bon ce genre de fonction est adaptable aux tri de n'importe quoi tant qu'on lui apporte une fonction qui compare deux elements.
en l'occurence ici :

int strCmp(char *str1, char *str2)
{
int i = 0;
while (str1[i] == str2[i] && str1[i] != 0 && str2[i] != 0) i++;
return (str2[i] - str1[i]);
}

pour classer des nombre dans l'odre decroissant :

int strCmp(int a, int b)
{
return a-b; // ou b-a j'ai pas réfléchi
}

et ainsi de suite.....