2017-05-03 4 views
-2

Je n'arrive pas à comprendre quel est le problème avec mon code, Im obtenant un nombre absurdement grand d'opérations pour mon code de tri d'insertion. J'espérais de l'aide.opérations comptant la sélection de bulles d'insertion

int insertionSort(int arr[], int n, int &operations) 
{ 
    clock_t start = clock(); 
    int i, key, j; 
    for (i = 1; i < n; i++) 
    { 
     key = arr[i]; 
     j = i - 1; 

     while (j >= 0 && arr[j] > key) 
     { 
      arr[j + 1] = arr[j]; 
      j = j - 1; 
      operations++; 
     } 
     arr[j + 1] = key; 
    } 
    clock_t end = clock(); 
    return end - start; 
} 
+0

ne devrait pas vous mettre '= opérations avant 0' en boucle? En ce moment, vous ajoutez simplement à la valeur que 'operations 'avait quand la fonction a été appelée, ce qui aurait pu être n'importe quoi. – PaulMcKenzie

Répondre

0

En se référant à ce poste: How to count comparisons and swaps in insertion sort? (JAVA)

Vous pouvez compter le nombre d'opérations que:

long int operations=0; 
int insertionSort(int arr[], int n, int &operations) 
{ 
    clock_t start = clock(); 
    int i, key, j; 
    for (i = 1; i < n; i++) 
    { 
     key = arr[i]; 
     j = i - 1; 

     while (1) 
     { 
      operations++; 
      if((j>=0) && (arr[j]>key)){ 
       arr[j + 1] = arr[j]; 
       j = j - 1; 
      } 
      else break; 
     } 
     arr[j + 1] = key; 
    } 
    clock_t end = clock(); 
    return end - start; 
} 
+0

Et si 'operations' entrait avec un nombre absurde, votre solution ne fonctionnerait pas. Il n'y a aucune indication que 'operations' a été initialisé en dehors de la fonction. – PaulMcKenzie

+0

Modifications effectuées selon le commentaire de @PaulMcKenzie. Je vous remercie. –