List.Binarysearch

olibara Messages postés 666 Date d'inscription dimanche 16 décembre 2007 Statut Membre Dernière intervention 11 mars 2010 - 12 févr. 2008 à 18:02
Lutinore Messages postés 3246 Date d'inscription lundi 25 avril 2005 Statut Membre Dernière intervention 27 octobre 2012 - 12 févr. 2008 à 19:41
Bonjour,

Je voudrais faire une recherche dans une liste triée par construction
Cette liste contient un tableau de structures
struct MyStuct
{
  int Id;
  int dum;
  int dum1;
}

La liste est triée sur Id par construction
Si j'ai bien compris je dois passer un element contenant la Clef de recherche

MyStruct kElem = new MyStruct;

kElm.Id=1234;
int idx;
idx=MyList.binarysearch(kElem);

Si je fais ca je recois faiked to compare two element inthe array ?
Quel est le probleme

1- Suis je obligé de trier la liste  apres construction ?
2- Dois je donner la fonction de comparaison
3- Je ne passe pas bien la clef de recherche ?

Merci pour votre aide....
Mais je n'ai pas beaucoup de reponse aujourd'hui

J'ai été désagréable avec quelqu'un ?
Je suis vraiment trop idiot ?

1 réponse

Lutinore Messages postés 3246 Date d'inscription lundi 25 avril 2005 Statut Membre Dernière intervention 27 octobre 2012 41
12 févr. 2008 à 19:41
Salut, t'inquiète beaucoup de membres sont aux Techdays..

Oui pour faire une recherche binaire le tableau doit être trié.

public struct MyStruct
{
    public int Id;


    public MyStruct( int id )
    {
        this.Id = id;
    }
}



public class MyStructComparer : IComparer< MyStruct >
{
    public int Compare( MyStruct x, MyStruct y )
    {
        return x.Id - y.Id;
    }
}


public void SortAndSearch( )
{
    List< MyStruct > list = new List< MyStruct >( );
    list.AddRange( new MyStruct[ ]
        { new MyStruct( 6001 ), new MyStruct( 4001 ) } );


    MyStructComparer comparer = new MyStructComparer( );


    MessageBox.Show( String.Format( "Avant: {0} / {1}", list[ 0 ].Id, list[ 1 ].Id ) );
    list.Sort( comparer );
    MessageBox.Show( String.Format( "Apres: {0} / {1}", list[ 0 ].Id, list[ 1 ].Id ) );


    int index = list.BinarySearch( new MyStruct( 6001 ), comparer );
    MessageBox.Show( String.Format( "Index: {0}", index ) );


}
0
Rejoignez-nous