training

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

clochk.c (1241B)


      1 /* Exercise 6.15 */
      2 
      3 #include <stdio.h>
      4 #define SIZE 20
      5 
      6 int bs(int, const int [], int);
      7 void bsort(int [], int);
      8 
      9 int main()
     10 {
     11    int num[SIZE + 1] = { 0 };
     12    int i, j;
     13    int c = 1;
     14 
     15    int k;
     16    for(i = 1; i <= SIZE; i++) {
     17       do {
     18 	 printf("Give me a number (10-100): ");
     19 	 scanf("%d", &num[0]);
     20       } while(num[0] < 10 || num[0] > 100);
     21 
     22       bsort(num, SIZE);
     23 
     24       if(!bs(num[0], num, SIZE))
     25 	 printf("New number: %d\n", num[c++] = num[0]);
     26    } /* end for (i) */
     27 
     28    return 0;
     29 } /* E0F main */
     30 
     31 /* Binary search: find (?) key in the array v[] */
     32 int bs(int key, const int v[], int s)
     33 {
     34    int i, m;
     35    int low = 1;
     36 
     37    while(low <= s) {
     38       m = (low + s) / 2;
     39       if(key == v[m])
     40 	 return m;
     41 
     42       if(key < v[m])
     43 	 s = m - 1;
     44       else
     45 	 low = m + 1;
     46    }
     47    return 0;
     48 
     49 } /* eof bs() */
     50 
     51 /* Order an array using Bubble Sort algorithm */
     52 void bsort(int v[], int s)
     53 {
     54    int i, j;
     55    int t_val, t_val2;
     56 
     57    for(i = 0; i < s; i++) {
     58       for(j = 1; j < s - i; j++) {
     59          if(v[j] > v[j + 1]) {
     60             t_val = v[j];
     61             v[j] = v[j + 1];
     62             v[j + 1] = t_val;
     63          } /* end if */
     64       } /* end for (j) */
     65 
     66       if(t_val2 == t_val)
     67          break;
     68    } /* end for (i) */
     69 
     70 } /* eof bsort() */
     71