CS50x threads to aide as a supplementary resource › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 3: [Algorithms] – Linear Search, Binary Search, Bubble Sort, Selection Sort, Recursion, Merge Sort › Swapping numbers in array
Tagged: arrays, linear search, sorting arrays, swapping, swapping in c
- This topic is empty.
-
AuthorPosts
-
April 2, 2022 at 11:00 am #319
#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); } }
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]
-
AuthorPosts
- You must be logged in to reply to this topic.