C Custom Bubble Sort

C Custom Bubble Sort - C++ - Programmation

Marsh Posté le 20-07-2022 à 13:05:01    

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]);

Reply

Marsh Posté le 20-07-2022 à 13:05:01   

Reply

Marsh Posté le 20-07-2022 à 14:43:11    

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 !
Reply

Marsh Posté le 22-07-2022 à 11:25:12    

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
Reply

Sujets relatifs:

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed