stoneharry

Untitled

Jan 26th, 2014
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. //Always use meaningful names for types
  4. typedef unsigned char boolean;
  5. #define True 't'
  6. #define FALSE (!True)
  7.  
  8. //this is a really neat trick for swapping values efficiently
  9. void swap(long* a,long *b) { *a=*a^*b;*b=*b^*a;*a=*a^*b; }
  10.  
  11. //Here's a readability improvement
  12. #define until(condition) while(!(condition))
  13.  
  14. int main(int n, char*args[]){
  15.   double *d;
  16.   int i;
  17.   char input[5];  //should be long enough for most doubles.
  18.   boolean sorted = FALSE;
  19.  
  20.   //In C, you need to specify the array size beforehand, so ask
  21.   printf("Please enter the length of the array\n");
  22.   gets(input);
  23.   //scan the input string and convert to a value
  24.   sscanf(input,"%s",&input[0]);
  25.   n=(long)atol(input);
  26.  
  27.   //allocate space, make sure you get the order of arguments right.
  28.   d = calloc(sizeof(double),n);
  29.  
  30.   //Get and sort the array
  31.   until (sorted) {
  32.  
  33.      for (i=0;i<n;i++) {
  34.         //It's important to always ask nicely
  35.         printf("Please enter the %d%s array item\n",i,i==1?"st":"th");
  36.         scanf("%lf",d+i);
  37.      }
  38.      //do a compare and exchange sort:
  39.      sorted = !sorted;  //not sorted
  40.      //check all the items
  41.      printf("%d %d\n",i,n);
  42.      for (i=1;i<n;i++) {
  43.         //compare
  44.         if (d[i]<d[i-1]) {
  45.           //exchange
  46.           swap(d+i,d+i-1);
  47.           sorted = FALSE;
  48.         }
  49.      }
  50.      //show results
  51.      printf("The array is%ssorted\n",sorted?" ":" not "); }
  52.   //use the --> "downto operator" for counting downto 0.
  53.   for (;n-->0;) printf("%lf\n",*d++);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment