Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #include <string.h>
- #include <math.h>
- // https://www.youtube.com/watch?v=6qiNJWw5aLI&feature=emb_title
- int main()
- {
- int i, temp, swapped; // declare counting variable i, "temp" for whenever we need to tempoararily store a number, swapped is either going to be 0 or 1
- int HowMany = 10;
- int goals[HowMany];
- for (i = 0; i < HowMany; i++)
- {
- goals[i] = (rand() % 25) + 1;
- }
- printf("Original unsorted array: \n");
- for (i = 0; i < HowMany; i++)
- {
- printf("%d \n", goals[i]);
- }
- while (1) // this while loop is set to "true (1)" and it'll run forever until an exit condition is met
- {
- swapped = 0;
- printf("Swapped value %d", swapped);
- for (i = 0; i < HowMany -1; i++) // this forloop will have to take every number and compare it to the number after. We added "-1" because the last number doesnt have anything after to compare itself to
- {
- if (goals[i] > goals[i + 1]) // this forloop will go through all of the numbers in the array start to finish and swap them
- {
- temp = goals[i]; // on this line, we take the first number being compared and store it in a tempoary variable
- goals[i] = goals[i + 1]; // this line takes the second number being compared and moves it into where the first number used to exist
- goals[i + 1] = temp; // now take the first number which was moved to "temp" and store it in where the second number used to be
- swapped = 1; // update the swapped to equal 1 to indicate that the list of array elements is not in order yet, and we need to go through the list again.
- }
- }
- if (swapped == 0) // if swapped is == to 0 after the above loop completes
- {
- break; // break this loop to indicate when the entire array has been sorted.
- }
- }
- printf("Sorted array: \n"); // print out the sorted array so we can see it
- for (i = 0; i < HowMany; i++)
- {
- printf("%d \n", goals[i]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement