Advertisement
thenewboston

C Programming Tutorial - 41 - Sorting Arrays

Aug 22nd, 2014
714
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 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. int main()
  8. {
  9.     int i, temp, swapped;
  10.     int howMany = 10;
  11.     int goals[howMany];
  12.  
  13.     //create an array of random numbers
  14.     for(i=0; i<howMany; i++){
  15.         goals[i] = ( rand()%24 )+1;
  16.     }
  17.  
  18.     printf("Original List\n");
  19.     for(i=0; i<howMany; i++){
  20.         printf("%d \n", goals[i]);
  21.     }
  22.  
  23.     while(1){
  24.  
  25.         swapped = 0;
  26.  
  27.         //comparing each number to number after it
  28.         //last number won’t have a number after, so howMany -1
  29.         for(i=0; i<howMany-1; i++){
  30.             //if first number bigger, swap them
  31.             if(goals[i]>goals[i+1]){
  32.                 int temp = goals[i]; //we are going to replace it
  33.                 goals[i] = goals[i+1]; //replace first with second
  34.                 goals[i+1] = temp; //replace second with first
  35.                 swapped = 1;
  36.             }
  37.         }
  38.  
  39.         if(swapped==0){
  40.             break;
  41.         }
  42.  
  43.     }
  44.  
  45.     //print out the sorted list
  46.     printf("\nSorted List\n");
  47.     for(i=0; i<howMany; i++){
  48.         printf("%d \n", goals[i]);
  49.     }
  50.  
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement