Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
750 connectés 

  FORUM HardWare.fr
  Programmation
  C++

  C Custom Bubble Sort

 


 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

C Custom Bubble Sort

n°2422481
joun17
be cool
Posté le 20-07-2022 à 13:05:01  profilanswer
 

I'm attempting to figure out what's wrong with my code; I'm new to C but have a lot of experience with Java. I created my own "lazy" bubble sort implementation using 8 integers. However, it results in an indefinite loop. I read several articles about Bubble sort in C, https://www.scaler.com/topics/c-bubble-sort/.
 
Attempting to sort 8 integers from greatest to smallest and using the counter to detect when all values are sorted.
 

Code :
  1. #include <stdio.h>
  2. int main()
  3. {
  4. int array[8];
  5. int counter =0;
  6. int storage=0;
  7. int i;
  8. printf("Please enter 8 numbers:" );
  9. scanf("%d%d%d%d%d%d%d%d",&array[0],&array[1],&array[2],&array[3],&array[4],&array[5],&array[6],&array[7]);
  10. while (counter!=7)
  11. {
  12.     counter =0;
  13. for (i=0; i<=6;i++)
  14. {
  15.     if (array[i]<=array[i++])
  16.     {
  17.         storage = array[i];
  18.         array[i]= array[i++];
  19.         array[i++]= storage;
  20.     }
  21.     else
  22.     {
  23.         counter++;
  24.     }
  25. }
  26. }
  27. printf("%d%d%d%d%d%d%d%d",array[0],array[1],array[2],array[3],array[4],array[5],array[6],array[7]);

mood
Publicité
Posté le 20-07-2022 à 13:05:01  profilanswer
 

n°2422490
Farian
Posté le 20-07-2022 à 14:43:11  profilanswer
 

Hello !  
 
The swap should not be done if the two values are equal, only if "array[i] < array[i++]" because if they are equal, swapping is useless and leads directly to an infinite loop.
 
By the way, shouldn't there be spaces in the scanf first parameter ?
 
Regards !


---------------
On n'est jamais très fort pour ce calcul !
n°2422616
slr56
Tout problème a sa solution.
Posté le 22-07-2022 à 11:25:12  profilanswer
 

Hello, you are on a french forum so you have to write in french.
 
Thank you.


---------------
Configurations type du moment : https://forum.hardware.fr/hfr/Hardw [...] 1331_1.htm  https://www.jouannetphotographe.com

Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation
  C++

  C Custom Bubble Sort

 

Sujets relatifs
img qui sort de son conteneur liLangage C/ projet gestion de véhicules
C++ ou C: compréhension du fonctionement du hardwareLa fenêtre de commande clignote lors du débogage de programmes C++ dan
[C] Refresh d'un fichier ouvert[C#] Code décompilé ne recompile pas...
[resolut]passage d'un tableau de structure à une DLL C[resolu] [C] [GCC] static volatile variable et warning (ou pas)
Programme tri à bulle C++[C] Problème de pointeur
Plus de sujets relatifs à : C Custom Bubble Sort


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR