• This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #319
    admin
    Keymaster
      
      
      #include<stdio.h>
      #include<cs50.h>
      #include<string.h>
      int main(void)
      {
      int numbers[] = {90,80,7,6,5};
      int t = 0;
          for (int i = 0; i < 5; i++)
          {
              if (numbers < numbers)
              {
              t = numbers;
              numbers = numbers;
              numbers = t;
              }
          }
              for(int i = 0; i < 5; i++)
              {
              printf("%d",numbers);
              }
      }

       

       

       

      What the above code doing is comparing 90 with 80 and then swapping. So 80,90,7,6,5.

      Next, swapping 90,7 to 7,90.

      Next swapping 90,6 to 6, 90.

      and then 90,5 to 5,90,

      Final output is 80,7,6,5,90.

      My aim is to have 5,6,7,80,90.

      The sorting process appears more tricky than I initially thought.

      Any clue how to proceed appreciated.

      UPDATE

      Here is the revised code after introducing swap counter which apparently working fine.

      
      
      #include<stdio.h>
      #include<cs50.h>
      #include<string.h>
      int main(void)
      {
      int numbers[] = {90,80,7,6,5};
      int t = 0;
      int swapcounter = -1;
          while (swapcounter != 0);
          {   
          swapcounter = 0;
              for (int i = 0; i < 5; i++)
              {
                  if (numbers < numbers)
                  {
                  t = numbers;
                  numbers = numbers;
                  numbers = t;
                  swapcounter = swapcounter + 1;
                  }
              }
          }
              for(int i = 0; i < 5; i++)
              {
              printf("%d\n",numbers);
              }
      }

      r/cs50 - Swapping numbers in array


      Reply


      Did you watch the short about bubble sort? https://cs50.harvard.edu/x/2022/shorts/bubble_sort/


      By the nature of the “for” it will only check each pair once. What you want is something that will repeat the for multiple times until you specify an end case.[learn_press_profile]

    Viewing 1 post (of 1 total)
    • You must be logged in to reply to this topic.
    Scroll to Top