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 :

Tri d'un tableau [Débutant]


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Invité
    Invité(e)
    Par défaut Tri d'un tableau
    Bonjour,
    Qulqu'un pourrait m'aider ? J'ai une fonction de tri de 2 string qui me permet de ne pas Array.Sort vu que Array.Sort utilise le tri naturel alors que je veux utiliser le tri alpabetique.

    Le probleme est que : je veux passer en parametre un tableau et en valeur de retour un tableau triée, non pas 2 strings.

    Merci

  2. #2
    Membre Expert
    Avatar de Sehnsucht
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Octobre 2008
    Messages
    847
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Lot et Garonne (Aquitaine)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Octobre 2008
    Messages : 847
    Par défaut
    Bonjour,

    L'ordre naturel de tri pour des string est l'ordre alphabétique (au moins celui pour la culture actuelle).
    De plus Array.Sort possède diverses surcharges permettant (le cas échéant) de spécifier le type de comparaison souhaitée (via IComparer ou Comparison)
    Donc en l'état, il va falloir être plus précis car ce n'est pas très clair

    Cordialement !

  3. #3
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Paris (Île de France)

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

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Par défaut
    Montre le code que tu as, et décris plus précisément le tri que tu veux obtenir

  4. #4
    Invité
    Invité(e)
    Par défaut
    Le probleme est que pour trier cette suite avec Array.Sort() :
    a1
    a12
    a20
    a21
    a100
    a101,
    on a :
    a1
    a12
    a100
    a101
    a20
    a21
    mais moi je veux du tri normale.

    Pour ce faire, j'ai utilisé le code ci-dessous pour la comparaison de 2 strings.
    Et pour finaliser, je veux passer un tableau tout entier a la fonction de tri, en utilisant la classe dans le code, au lieu de 2 strings seulement.

    vla le code entier pour le tri entre 2 string, en gros ce code fait la comparaison entre 2 string en mot par mot
    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
     
    public static class StringComparator
        {
            private enum ChunkType {Alphanumeric, Numeric};
     
     
            private static bool InChunk(char ch, char otherCh)
            {
                ChunkType type = ChunkType.Alphanumeric;
     
                if (char.IsDigit(otherCh))
                {
                    type = ChunkType.Numeric;
                }
     
                if ((type == ChunkType.Alphanumeric && char.IsDigit(ch)) || (type == ChunkType.Numeric && !char.IsDigit(ch)))
                {
                    return false;
                }
                return true;
            }
     
            /// <summary>
            /// Compare les 2 objets
            /// </summary>
            /// <param name="x">objet 1</param>
            /// <param name="y">objet 2</param>
            /// <returns>0 si erreur, </returns>
            public static int Compare(object x, object y)
            {
                String s1 = x as string;
                String s2 = y as string;
     
                if (s1 == null || s2 == null)
                    return 0;
     
                int thisMarker = 0, thisNumericChunk = 0;
                int thatMarker = 0, thatNumericChunk = 0;
     
                while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
                {
                    if (thisMarker >= s1.Length)
                        return -1;
     
                    else if (thatMarker >= s2.Length)
                        return 1;
     
                    char thisCh = s1[thisMarker];
                    char thatCh = s2[thatMarker];
     
                    StringBuilder thisChunk = new StringBuilder();
                    StringBuilder thatChunk = new StringBuilder();
     
                    while ((thisMarker < s1.Length) && (thisChunk.Length==0 ||InChunk(thisCh, thisChunk[0])))
                    {
                        thisChunk.Append(thisCh);
                        thisMarker++;
     
                        if (thisMarker < s1.Length)
                           thisCh = s1[thisMarker];  
                    }
     
                    while ((thatMarker < s2.Length) && (thatChunk.Length==0 ||InChunk(thatCh, thatChunk[0])))
                    {
                        thatChunk.Append(thatCh);
                        thatMarker++;
     
                        if (thatMarker < s2.Length)
                            thatCh = s2[thatMarker];
                    }
     
                    int result = 0;
                    // If both chunks contain numeric characters, sort them numerically
                    if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
                    {
                        thisNumericChunk = Convert.ToInt32(thisChunk.ToString());
                        thatNumericChunk = Convert.ToInt32(thatChunk.ToString());
     
                        if (thisNumericChunk < thatNumericChunk)
                           result = -1;
     
                        if (thisNumericChunk > thatNumericChunk)
                           result = 1;    
                    }
                    else
                        result= thisChunk.ToString().CompareTo(thatChunk.ToString());
     
                    if (result != 0)
                        return result;  
                }
                return 0;
            }
     
     
        }

  5. #5
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Paris (Île de France)

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

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Par défaut
    Citation Envoyé par Andrian Voir le message
    Le probleme est que pour trier cette suite avec Array.Sort() :
    a1
    a12
    a20
    a21
    a100
    a101,

    on a :

    a1
    a12
    a100
    a101
    a20
    a21
    mais moi je veux du tri normale.
    Bah ça c'est le tri alphabétique justement... Donc en fait ce que tu veux ce n'est pas un tri alphabétique, mais un tri qui tienne compte de la valeur du nombre

    Moyennant quelques petites modifs, tu peux utiliser ta classe StringComparator avec Array.Sort :

    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
     
        public class StringComparator : IComparer<string>
        {
            private enum ChunkType {Alphanumeric, Numeric};
     
     
            private static bool InChunk(char ch, char otherCh)
            {
                ChunkType type = ChunkType.Alphanumeric;
     
                if (char.IsDigit(otherCh))
                {
                    type = ChunkType.Numeric;
                }
     
                if ((type == ChunkType.Alphanumeric && char.IsDigit(ch)) || (type == ChunkType.Numeric && !char.IsDigit(ch)))
                {
                    return false;
                }
                return true;
            }
     
            public int Compare(string s1, string s2)
            {
     
                if (s1 == null || s2 == null)
                    return 0;
     
                int thisMarker = 0, thisNumericChunk = 0;
                int thatMarker = 0, thatNumericChunk = 0;
     
                while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
                {
                    if (thisMarker >= s1.Length)
                        return -1;
     
                    else if (thatMarker >= s2.Length)
                        return 1;
     
                    char thisCh = s1[thisMarker];
                    char thatCh = s2[thatMarker];
     
                    StringBuilder thisChunk = new StringBuilder();
                    StringBuilder thatChunk = new StringBuilder();
     
                    while ((thisMarker < s1.Length) && (thisChunk.Length==0 ||InChunk(thisCh, thisChunk[0])))
                    {
                        thisChunk.Append(thisCh);
                        thisMarker++;
     
                        if (thisMarker < s1.Length)
                           thisCh = s1[thisMarker];  
                    }
     
                    while ((thatMarker < s2.Length) && (thatChunk.Length==0 ||InChunk(thatCh, thatChunk[0])))
                    {
                        thatChunk.Append(thatCh);
                        thatMarker++;
     
                        if (thatMarker < s2.Length)
                            thatCh = s2[thatMarker];
                    }
     
                    int result = 0;
                    // If both chunks contain numeric characters, sort them numerically
                    if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
                    {
                        thisNumericChunk = Convert.ToInt32(thisChunk.ToString());
                        thatNumericChunk = Convert.ToInt32(thatChunk.ToString());
     
                        if (thisNumericChunk < thatNumericChunk)
                           result = -1;
     
                        if (thisNumericChunk > thatNumericChunk)
                           result = 1;    
                    }
                    else
                        result= thisChunk.ToString().CompareTo(thatChunk.ToString());
     
                    if (result != 0)
                        return result;  
                }
                return 0;
            }
     
     
        }
    Modifications :
    - la classe n'est plus statique
    - elle implémente IComparer<string>
    - la méthode Compare n'est plus statique et prend en paramètre des string, pas des object

    Utilisation :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Array.Sort(leTableau, new StringComparator());

  6. #6
    Membre Expert
    Avatar de Sehnsucht
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Octobre 2008
    Messages
    847
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Lot et Garonne (Aquitaine)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Octobre 2008
    Messages : 847
    Par défaut
    Il me semble qu'on peut aussi utiliser StrCmpLogical en PInvoke pour obtenir la même chose (enfin là ça sera plutôt un Comparison) enfin c'est à vérifier j'ai pas vraiment de quoi tester sous la main.

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

Discussions similaires

  1. Tri d'un tableau en 2D
    Par sniperseb dans le forum C
    Réponses: 4
    Dernier message: 05/01/2006, 16h33
  2. Réponses: 6
    Dernier message: 16/09/2005, 10h30
  3. tri d'un tableau à 2 dimensions
    Par dede92 dans le forum C
    Réponses: 4
    Dernier message: 19/02/2005, 18h29
  4. [langage] Probleme de tri d'un tableau de tableau
    Par Ludo167 dans le forum Langage
    Réponses: 1
    Dernier message: 25/08/2004, 10h32
  5. [] Tri d'un tableau par ordre alphabétique
    Par cafeine dans le forum VB 6 et antérieur
    Réponses: 3
    Dernier message: 17/09/2002, 08h43

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