Advertisement
bocajbee

sort.c

Mar 29th, 2020
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4. #include <string.h>
  5. #include <math.h>
  6.  
  7. // https://www.youtube.com/watch?v=6qiNJWw5aLI&feature=emb_title
  8.  
  9. int main()
  10. {
  11.     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
  12.     int HowMany = 10;
  13.     int goals[HowMany];
  14.  
  15.     for (i = 0; i < HowMany; i++)
  16.     {
  17.         goals[i] = (rand() % 25) + 1;
  18.     }
  19.  
  20.     printf("Original unsorted array: \n");
  21.  
  22.     for (i = 0; i < HowMany; i++)
  23.     {
  24.         printf("%d \n", goals[i]);
  25.     }
  26.  
  27.     while (1)  // this while loop is set to "true (1)" and it'll run forever until an exit condition is met
  28.     {
  29.         swapped = 0;
  30.         printf("Swapped value %d", swapped);
  31.  
  32.         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
  33.         {
  34.             if (goals[i] > goals[i + 1]) // this forloop will go through all of the numbers in the array start to finish and swap them
  35.             {
  36.                 temp = goals[i]; // on this line, we take the first number being compared and store it in a tempoary variable
  37.                 goals[i] = goals[i + 1]; // this line takes the second number being compared and moves it into where the first number used to exist
  38.                 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
  39.                 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.
  40.             }
  41.         }
  42.         if (swapped == 0) // if swapped is == to 0 after the above loop completes
  43.         {
  44.             break;  // break this loop to indicate when the entire array has been sorted.
  45.         }
  46.     }
  47.  
  48.     printf("Sorted array: \n"); // print out the sorted array so we can see it
  49.  
  50.     for (i = 0; i < HowMany; i++)
  51.     {
  52.         printf("%d \n", goals[i]);
  53.     }
  54.  
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement