training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

bsort2.c (1041B)


      1 /* Exercise 6.11 *
      2 
      3 /* Bubble Sort */
      4 
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <time.h>
      8 
      9 #define SIZE 10
     10 
     11 void parray(int [], int);
     12 
     13 int main()
     14 {
     15    int array[SIZE];
     16    int i, j, t_val;
     17 
     18    srand( time(NULL) );
     19 
     20    /* assign a random value to every element of array[] */
     21    for(i = 0; i < SIZE; i++) {
     22       array[i] = 1 + rand() % 999;
     23    }
     24 
     25    printf("This is the array before order:\n");
     26    parray(array, SIZE);
     27 
     28    /* bubble sort */
     29    int t_val2;
     30    for(i = 0; i < SIZE; i++) {
     31       for(j = 0; j < SIZE - i; j++) {
     32 	 if(array[j] > array[j + 1]) {
     33 	    t_val = array[j];
     34 	    array[j] = array[j + 1];
     35 	    array[j + 1] = t_val;
     36 	 } /* end if */
     37       } /* end for (j) */
     38 
     39       if(t_val2 == t_val)
     40          break;
     41 
     42    } /* end for (i) */
     43 
     44    printf("\nThis is the array after the order:\n");
     45    parray(array, SIZE);
     46 
     47    printf("\n");
     48 
     49    return 0;
     50 } /* E0F main */
     51 
     52 /* print an array */
     53 void parray(int a[], int size)
     54 {
     55    int i;
     56 
     57    for(i = 0; i < size; i++)
     58       printf("%d ", a[i]);
     59 
     60    printf("\n");
     61 
     62 } /* eof parray() */
     63