Tri d'une matrice sur la colonne choisie

Tri d'une matrice sur la colonne choisie

Messagepar bigBenTem » 10 Juin 2010 à 09:55

Le but est de trier une matrice de N lignes et de N colonnes sur une colonne passée en paramètre.

Attention le tri n'est pas optimum il ne pourra pas être utiliser pour de grosses matrices.

Code : Tout sélectionner
Sub Click(Source As Button)
   Dim nbCol As Integer
   Dim nbLig As Integer
   dim triCol as integer
   nbCol = 10
   nbLig = 20
   triCol = 2 'Colonne de référence pour le tri

   Redim tabToSort(nbLig-1, nbCol-1 ) As Variant
   
   ' Génération du tableau
   For i=0 To Ubound( tabToSort )
      For j=0 To nbCol-1
         tabToSort( i, j ) = Round( Rnd( 1 ) * 100, 2 )
         tabToSort( i, j ) = Round( Rnd( 1 ) * 100, 2 )
         tabToSort( i, j ) = Round( Rnd( 1 ) * 100, 2 )
      Next
   Next
   
   
   ' Affichage du tableau original
   For i=0 To Ubound( tabToSort )
      For j=0 To nbCol-1
         eltaff = eltaff & "[ " & tabToSort( i, j ) & " ] "
      Next
      Print "[" + eltaff + "]"
      eltaff=""
   Next
   
   ' Tri du tableau
   Print "Sorting table ...."

   Call SortTable( tabToSort , nbCol, triCol)
   Print "Table sorted !"
   
   ' Affichage du tableau final
   For i=0 To Ubound( tabToSort )
      For j=0 To nbCol-1
         eltaff = eltaff & "[ " & tabToSort( i, j ) & " ] "
      Next
      Print "[" + eltaff + "]"
      eltaff=""
   Next
End Sub


Fonctions appelée :
Code : Tout sélectionner
Function SortTable( tabToSort As Variant , nbCol As Integer , triCol As Integer)
   Dim sw As Boolean
   Dim i As Integer
   Dim j As Integer
   
   Do
      noSwitch = True
      
      For i=0 To Ubound( tabToSort ) - 1
         If tabToSort( i, triCol-1 ) > tabToSort( i+1, triCol-1 ) Then
            Call SwitchTable( tabToSort, i, i+1, nbCol )
            noSwitch = False
         End If
      Next
      
      
   Loop While Not noSwitch
End Function

Sub SwitchTable( tabToSort As Variant, i As Integer, j As Integer , nbCol As Integer)
   For k=0 To nbCol-1
      tmp = tabToSort( i, k )
      
      tabToSort( i, k ) = tabToSort( j, k )
      
      tabToSort( j, k ) = tmp
   Next
End Sub
Avatar de l’utilisateur
bigBenTem
Apprenti-posteur
Apprenti-posteur
 
Message(s) : 105
Inscrit(e) le : 07 Fév 2007 à 11:34
Localisation : Choisy Le Roi

Retour vers Fonctions de tris